<?php

/**

 * Created by PhpStorm.

 * User: Administrator

 * Date: 2021/12/6

 * Time: 14:51

 */



namespace app\api\controller;



use app\admin\controller\BydDesignerMake;
use app\admin\controller\Cache;
use app\admin\controller\Cwxx;
use app\admin\model\Apply;
use app\admin\model\Bpay;
use app\admin\model\BydAgreement;
use app\admin\model\BydDesigner;
use app\admin\model\BydDesignerArea;
use app\admin\model\BydDestri;
use app\admin\model\BydDispro;
use app\admin\model\BydDistri;
use app\admin\model\BydIden;
use app\admin\model\BydLoding;
use app\admin\model\BydOrderTuishop;
use app\admin\model\BydPl;
use app\admin\model\BydPots;
use app\admin\model\BydSdexpress;
use app\admin\model\BydShopActivity;
use app\admin\model\BydShopIcon;
use app\admin\model\BydShopOrderSet;

use app\admin\model\BydShopPl;
use app\admin\model\BydUserAg;
use app\admin\model\BydUsercupons;
use app\admin\model\BydUserSale;
use app\admin\model\BydUserTy;
use app\admin\model\Cupons;
use app\admin\model\DesPf;
use app\admin\model\Sermoney;
use app\admin\model\SoleAgency;
use app\admin\model\SoleBuilding;
use app\admin\model\Sorce;
use app\admin\model\Temrela;
use app\admin\model\Train;
use app\api\model\BydIdentity;
use app\common\controller\News;
use app\common\controller\Zhihuixin;
use think\db;

//require EXTEND_PATH.'guzzlehttp/guzzle/src/Client.php';

use app\admin\model\BydAddress;

use app\admin\model\BydCupon;

use app\admin\model\BydMycupon;

use app\admin\model\BydOrderSon;

use app\admin\model\BydOrderTui;

use app\admin\model\BydShopCart;

use app\admin\model\BydShopOrder;

use app\common\controller\Api;

use base\Wx;

use http\Client;
use function fast\e;


class Bydshop extends Api

{

    /**

     * 无需登录的方法,同时也就不需要鉴权了

     * @var array

     */

    protected $noNeedLogin = ['*'];



    /**

     * 商城产品中心

     */

    public function shopindex(){

        $arr=\app\api\model\BydShop::shopindex();

        if ($arr){
            $this->success(__('请求成功'),['status' => $arr]);
        }else{
            $this->error('请求失败');
        }

    }

    /**
     * 商城产品中心查看更多分类
     */

    public function seemore(){

       $arr=\app\api\model\BydShop::category();

      if($arr==null){

          $this->error('请求成功,暂无数据');

      }else{

          $this->success(__('请求成功'),['status' => $arr]);

      }

    }

    /**

     * 取消退款
     * @param integer $orderid` '订单的id',

     */

    public function qxorder(){
        $byd = 0;
        $data = $this->request->request('');
        $deal=BydShopOrder::where('orderid',$data['orderid'])->find();
        if($deal['returnstate'] != -1)
        {
          $byd=BydShopOrder::where('orderid',$data['orderid'])->update(['state'=>$deal['returnstate'],'returnstate'=>-1]);
          $res = \app\admin\model\BydOrderTui::where('orderid',$data['orderid'])->delete();


        }


        if($byd){

            $this->success(__('取消成功'));

        }else{

            $this->error('取消失败');

        }

    }



    /**

     * 产品中心分类下商品
     * @param integer $id` '分类id',
     * @param integer $switch` '综合1价格升序2为价格降序3为销量',

     * id 分类id

     * switch 0综合1价格升序2为价格降序3为销量

     */

    public function categoryshop(){

        $data = $this->request->request('id');

        $shop=\app\api\model\BydShop::categoryshop($data);

        if($shop==null){

            $this->error('请求成功,暂无数据');

        }else{

            $this->success(__('请求成功'),['status' => $shop]);

        }

    }
    /**
     * 积分商品渲染
     */
    public function scoregoods(){
        $where['switch']=1;
        $where['shoptage']=1;
        $where['deletetime']=null;
        $find= \app\api\model\BydShop::where($where)->paginate(20);
        if(empty($find)){
            $this->error('暂无数据');
        }else{
            $this->success(__('请求成功'),['status' => $find]);
        }
    }
    /**
     * 商品详情
     *  @param integer $id` '产品id',
     * @param integer $user_id` '用户id',
     *
     * id  产品id
     * user_id

     */

    public function shopxq(){

        $id = $this->request->request('');

        $shopxq=\app\api\model\BydShop::shopxq($id);

        if ($shopxq){

            $this->success(__('请求成功'),['status' => $shopxq]);

        }else {

            $this->error('请求失败');

        }

    }

        /**

         * 商品评价

         * @ApiMethod (POST)

         * @param integer $shopid 商品的id

         * @param integer $userid 用户的id

         * @param varchar $content 评价的内容

         * @param varchar $image 评价的内容

         */

        public function pl(){

            $data = $this->request->request('');

            $creat=\app\api\model\BydShop::pl($data);

            if($creat==null){

                $this->error('请求失败');

            }else{

                $this->success(__('请求成功'));

            }

        }

    /**

     *   回复评论

     * @ApiMethod (POST)

     * @param integer $pl_id 评论的id

     * @param integer $pl_user_id 被回复人的id

     * @param integer $userid 用户的id

     * @param varchar $content 评价的内容

     */

        public function plhf(){

            $data = $this->request->request('');

            $hf=\app\api\model\BydShop::hfpl($data);

            if($hf==null){

                $this->error('请求失败');

            }else{

                $this->success(__('请求成功'));

            }

        }

        /**

         * 查看全部评论

         *  @ApiMethod (POST)

         * @param integer $shopid 商品的id

         */

        public function allpl(){

            $data = $this->request->request('');

            $all=\app\api\model\BydShop::allcomment($data);

            if($all==null){

                $this->error('请求失败');

            }else{

                $this->success(__('请求成功'),['status' => $all]);

            }

        }

        /**

         * 商品模糊查询

         *   @ApiMethod (POST)

         * @param integer $name 搜索文字

         */

    public function shoplike(){

        $data = $this->request->request('');

        $all=\app\api\model\BydShop::shoplike($data);

        if($all==null){

            $this->error('请求成功,暂无数据');

        }else{

            $this->success(__('请求成功'),['status' => $all]);

        }

    }

    /**

     * 购物车展示
     * @param integer $id` '产品id',

     */

    public function shopcart(){

        $data = $this->request->request('');

        $cart=new \app\api\model\BydShop();

        $all=$cart->shopcart($data);

        if($all==null){

            $this->error('请求成功,暂无数据');

        }else{

            $this->success(__('请求成功'),['status' => $all]);

        }

    }

    /**

     * 订单设置

     */

    public function orderset(){

        $arr=BydShopOrderSet::select();

        if($arr){

            $this->success(__('请求成功'),['status' => $arr]);

        }else{

            $this->error('请求成功,暂无数据');

        }

    }

    /**  设置订单号

     * @return string

     */



    protected  function getOrderNumber($file="BYD")

    {

        @date_default_timezone_set("PRC");



        while (true) {

            //订购日期

            $order_date = date('Y-m-d');

            //订单号码主体（YYYYMMDDHHIISSNNNNNNNN）

            $order_id_main = date('YmdHis') . rand(1000, 9999);

            //订单号码主体长度

            $order_id_len = strlen($order_id_main);

            $order_id_sum = 0;



            for ($i = 0; $i < $order_id_len; $i++) {

                $order_id_sum += (int)(substr($order_id_main, $i, 1));

            }

            $order_id =$file.'_'.$order_id_main . str_pad((100 - $order_id_sum % 100) % 100, 2, '0', STR_PAD_LEFT);

            return $order_id;



        }

    }



    /**

     * 购物车立即支付/放弃支付
     * @param integer $user_id` '用户id',
     * @param integer $cartid` '购物车id',
     * @param integer $num` '商品数量',
     * @param integer $addressid` '地址的id',
     * @param integer $type` '为立即支付1为放弃支付',
     * @param integer $specidsize` '商品规格详情',

     * user_id 用户id

     *  cartid 购物车id

     * num 商品数量

     * addressid 地址的id

     * type 0为立即支付1为放弃支付

     * specidsize 商品规格详情

     */



    public function cartpay(){

        $data = $this->request->request('');

        $osn = $this->getOrderNumber();

        $user=\app\admin\model\BydUser::where( 'id',$data['user_id'])->find();

        $address=BydAddress::where('id',$data['addressid'])->find();//查询出地址
      //临时关系
        $tem=Temrela::where('user_id',$data['user_id'])->where('close',0)->find();
        if(empty($tem)){
            $tem['one']=0;
            $tem['two']=0;
            $tem['three']=0;
        }else{
            $tem['one']=$tem['pid'];
            $tem['two']=$tem['two'];
            $tem['three']=$tem['three'];
        }

        $uu=new BydUser();

        if($data['type']==0){
            $data['state']=1;//立即支付
        }else{
            $data['state']=0;//放弃支付
        }
        if($data['cuponsid']>0){
            $cup=BydCupon::where('id',$data['cuponsid'])->find();
            //$find=BydUsercupons::where('user_id',$data['user_id'])->where('coupons_id',$data['cuponsid'])->update(['state'=>1]);
            //if($cup['yh_price']>$data['price'])$this->error(__('优惠劵不可用'));
            $price=$data['price']+$data['dj'];
            $yh=$cup['yh_price'];
        }else{
            $price=$data['price']+$data['dj'];
            $yh=0;
        }
        $price=floor($price*100)/100;

       //$bl=\app\admin\model\BydShopOrder::find();

        if($data['cartid']==0){
            $productLists=db('byd_shop')->where('id',$data['shopid'])->find();

//            $first=$data['price']*$bl['first']/100;

            $adds = new BydShopOrder();

            $adds->data([
                'dzg'=>$data['dzg'],
                'orderid'  => $osn,
                'one'  =>  $tem['one'],
                'two'  =>  $tem['two'],
                'three'  =>  $tem['three'],
                'deposit'  =>  $data['dj'],
                'user_id'  => $data['user_id'],
                'state' =>  0,
                'productid' =>  $data['shopid'],
                'num' =>   $data['num'],
                'cuponsid'=>$data['cuponsid'],
                'price' => $price,// $data['price']
                'yh_price' => $yh,// $data['price']
                'addressid' =>   $data['addressid'],
                'address' =>   $address['title'],
                'addressxq' =>   $address['address'],
                'phone' =>   $address['phone'],
                'special' =>   $data['specid'],
                'specidsize' => $data['specidsize'],
                'username'=>$address['username'],
                'content'=>$data['content']
            ]);

            $adds->save();

                $add = new BydOrderSon();

            $add->data([
                'productname'=>$productLists['name'],
                'good_code'=>$productLists['good_code'],
                'porderid'  => $osn,
                'fwbl'  => $productLists['fwbl'],
                'tcbl'  => $productLists['tcbl'],
                'user_id'  => $data['user_id'],
                'state' =>  0,

                'productid' =>  $data['shopid'],

                'num' =>   $data['num'],

                'price' =>  $data['price'],

               // 'addressid' =>   $data['addressid'],

                'address' =>   $address['title'],

                //'addressxq' =>   $address['address'],

                //'phone' =>   $address['phone'],

                'special' =>   $data['specid'],

                'specidsize' => $data['specidsize'],

               'username'=>$address['username']

            ]);

            $add->save();

            if($add){
                \think\Cache::set('xd',1,3600);
                //微信支付

                $config = [

                    'app_id'    => 'wx00e9e5b843259a9d',

                    'mch_id'    => '1584376091',

                    'key'       => 'TjRUCktaUcR6RQqCksBtwKRY8KwSTC4M',

                    'secret'    => 'cce6015196dbba888133f9a3613b18b7',

                    'notify'    => 'http://bao.scwushen.com/index.php/api/notify/cg',

                ];

                $obj = new Wx($config);

                $money = $data['price'];//$data['price']

                $data = [
                    'body' => '宝云邸',
                    'out_trade_no' => $osn, //客户订单号,
                    'total_fee'=> $money * 100,
                    'trade_type'    => 'JSAPI',
                    'openid'    => $user['openid'],
                ];
                $ret = $obj->unifiedOrder( $data );
                return json($ret);
//                $wxpay=new Wxpay();
//                $arr = [
//                    'user_id'=>$data['user_id'],
//                    'order_id'  => $osn,
//                    'openid' =>$user['openid'],
//                    'status'=>1
//                ];
//
//                $pay=$wxpay->pay($arr);
//               return json(['code'=>1,'msg'=>'请求成功','data'=>$pay]);

            }

        }else{
//查看是否为预约订单商品

            $cart=BydShopCart::where('id','in',$data['cartid'])->select();
            $prices=BydShopCart::where('id','in',$data['cartid'])->sum('price');
            if(empty($cart)){
                return json(['code'=>0,'msg'=>'数据错误']);
            }

            if(empty($data['orderid'])){

                $data['yyid']=0;
//                $yyorder=\app\admin\model\BydDesignerMake::where('user_id',$data['user_id'])->where('state',1)->find();
//                if(empty($yyorder))   $this->error(__('预约订单有误'));
//                //预约订单里面的商品
//            $data['yyid']=$yyorder['orderid'];//预约单号
            }else{
                $yyorder=\app\admin\model\BydDesignerMake::where('user_id',$data['user_id'])->where('state',1)->find();
                if(empty($yyorder))   $this->error(__('预约订单有误'));
                //预约订单里面的商品
                $data['yyid']=$yyorder['orderid'];//预约单号

                $data['price']=$data['price']+$yyorder['price'];
//                $data['yyid']=0;
            }
            $add = new BydShopOrder();

//            foreach ($cart as $v){

            $add->data([
                'dzg'=>$data['dzg'],
                'orderid'  => $osn,
                'yyid'  => $data['yyid'],
                'user_id'  => $data['user_id'],
                'state' =>  0,
                'deposit'  =>  $data['dj'],
                'one'  =>  $tem['one'],
                'two'  =>  $tem['two'],
                'three'  =>  $tem['three'],
                //'productid' =>  $str,
                'num' =>   $data['num'],
                'swj'=>$data['swj'],
//                'jfprice' =>  $cart['jfprice']*$cart['num'],

                'cuponsid'=>$data['cuponsid'],
                'price' => $price,// $data['price']
                'yh_price' => $yh,// $data['price']

                'phone' =>   $address['phone'],

                'addressid' =>   $data['addressid'],

                'address' =>   $address['title'],

                'addressxq' =>   $address['address'],

                'username'=>$address['username'],

                'content'=>$data['content']


//                'state' =>   $data['state'],

//                'special' =>   $cart['specid'],

//                'specidsize' => $cart['specidsize'],

            ]);

            $add->save();

            if($add){
                \think\Cache::set('xd',1,3600);
//                foreach ($cart as $v){

////                    $id[]=$v['id'];

////                    $shopid[]=$v['shopid'];

//                }

            };

            foreach ($cart as $v){
                $productLists=db('byd_shop')->where('id',$v['shopid'])->find();

                $adds=new BydOrderSon();

//                $id[]=$v['id'];

//                $shopid[]=$v['shopid'];

                $adds->data([
                    'productname'=>$productLists['name'],
                    'good_code'=>$productLists['good_code'],
                    'porderid'  => $osn,
                    'fwbl'  => $productLists['fwbl'],
                    'tcbl'  => $productLists['tcbl'],
                    'user_id'  => $data['user_id'],

                    'state' =>  0,

                    'productid' =>  $v['shopid'],

                    'num' =>   $v['num'],

//                'jfprice' =>  $cart['jfprice']*$cart['num'],

                    'price' =>   $v['price'],

                    'addressid' =>   $data['addressid'],

                    'address' =>   $address['title'],

                    'addressxq' =>   $address['address'],

//                    'username'=>$address['username']

//                'state' =>   $data['state'],

                    'specid' =>   $v['specid'],
                    'special' =>   $v['specid'],

                    'specidsize' => $v['specidsize'],

                ]);

                $adds->save();

            }

           // $str = implode(",", $shopid);

//            print_r($cart);die;



//            foreach ($cart as $v){



            if($add){

              $deal=BydShopCart::where('id','in',$data['cartid'])->delete();

                //微信支付
                $config = [

                    'app_id'    => 'wx00e9e5b843259a9d',

                    'mch_id'    => '1584376091',

                    'key'       => 'TjRUCktaUcR6RQqCksBtwKRY8KwSTC4M',

                    'secret'    => 'cce6015196dbba888133f9a3613b18b7',

                    'notify'    => 'http://bao.scwushen.com/index.php/api/notify/cg',

                ];
                $zf=$data['price']-$data['dj'];
                $obj = new Wx( $config );

                $money = $zf;//$price

                $data = [

                    'body' => '宝云邸',

                    'out_trade_no' => $osn, //客户订单号,

                    'total_fee'=> $money * 100,

                    'trade_type'    => 'JSAPI',

                    'openid'    => $user['openid'],

                ];

                $ret = $obj->unifiedOrder( $data );



                //$deal=BydShopCart::destroy($data['cartid']);//删除购物车里面的数据

                return json($ret);

            }

//            $save['xfscore']=$user['xfscore']-$cart['jfprice'];

//            $wheree['id']=$data['user_id'];

//            $xfscore=$uu->isUpdate(true,($wheree))->save($save);



//            }

        }



    }



    /**
     * 加入购物车
     * @param integer $user_id` '用户id',
     * @param integer $shop_id` '商品id',
     * @param integer $specid` '商品规格id',
     * @param integer $specidsize` '商品规格详情',
     * @param integer $num` '商品数量',
     * @param integer $price` '价格',
     * @param integer $orderid` '预约订单id',
     * @param integer $swj` '0普通加入1三位家',
     *
     * user_id用户id
     * shop_id商品id
     * specid 商品规格id
     * specidsize 商品规格详情
     * num 商品数量
     * price 价格
     *  orderid  预约订单id
     * swj   0普通加入1三位家
     */

    public function addcart(){

        $data = $this->request->request('');

        $cart=\app\api\model\BydShop::addshopcart($data);

        if($cart==null){
            $this->error('添加失败');
        }else{
            $this->success(__('添加成功'));
        }

    }

    /**

     * 购物车删除
     * @param integer $id` '0购物车id',

     * id  购物车id

     */

    public function cartdel(){

        $data = $this->request->request('');



          $cart=\app\api\model\BydShop::shopcaredeal($data);

        if($cart==null){

            $this->error('删除失败');

        }else{

            $this->success(__('删除成功'));

        }

    }

    /**

     * 足迹删除
     * @param integer $id` '足迹id',

     */

    public function delfootxr(){

        $data = $this->request->request('');

        $del=\app\admin\model\BydShopMyfoot::where('id',$data['id'])->delete();

        if($del){

            $this->success(__('请求成功'));

        }else{

            $this->error('请求失败');

        }

    }

    /**

     * 我的足迹
     * @param integer $user_id` '用户id',
     * @param integer $shop_id` '商品id',

     *  user_id 用户id

     *  shop_id  商品id

     */

    public function myfoot(){

        $data = $this->request->request('');

        $foot=\app\api\model\BydShop::myfoot($data);

        if($foot==null){

            $this->error('添加失败');

        }else{

            $this->success(__('添加成功'));

        }

    }

    /**

     * 我的足迹渲染
     * @param integer $time` '时间',
     * @param integer $user_id` '用户id',

     * time 时间

     * user_id 用户id

     */

    public function myfootxr(){

        $data = $this->request->request('');

        $arr=\app\api\model\BydShop::myfootxr($data);

        if($arr==null){

            $this->error('暂无数据');

        }else{

            $this->success(__('请求成功'),['status'=>$arr]);

        }

    }

    /**

     * 待支付---确认支付
     * @param integer $id ` '订单的id',

     * id 订单的id

     */

    public function orderpay()

    {

        $data = $this->request->request('');

        //$ww['id']=$data['id'];

        $order = new BydShopOrder();

        $ww['id'] = $data['id'];

        $deal = $order->where($ww)->find();

        $user=\app\admin\model\BydUser::find($deal['user_id']);

        if ($deal) {

            //微信支付

            $config = [

                'app_id' => 'wx00e9e5b843259a9d',

                'mch_id' => '1584376091',

                'key' => 'TjRUCktaUcR6RQqCksBtwKRY8KwSTC4M',

                'secret' => 'cce6015196dbba888133f9a3613b18b7',

                'notify' => 'http://bao.scwushen.com/index.php/api/notify/cg',

            ];

            $obj = new Wx($config);

            $money = $deal['price'];

            $data = [

                'body' => '宝云邸',

                'out_trade_no' => $deal['orderid'], //客户订单号,

                'total_fee' => $money * 100,

                'trade_type' => 'JSAPI',

                'openid' => $user['openid'],

            ];

            $ret = $obj->unifiedOrder($data);

            return json($ret);

        }

    }

    /**
     * 待支付---取消订单
     * @param integer $id ` '订单的id',
     * id 订单的id
     */

    public function orderdzf(){

        $data = $this->request->request('');
        $oldstate = -1;

        //$ww['id']=$data['id'];

        $deal=BydShopOrder::find($data['id']);
        if($deal['cuponsid']>0){
            $find=BydUsercupons::where('user_id',$deal['user_id'])->where('coupons_id',$deal['cuponsid'])->update(['state'=>0]);
        }
        $oldstate = $deal['state'];
        $add = new BydOrderTui();

        $add->data([

            'orderid'  =>$deal['orderid'],

            'content' =>  '不想要了',

            'user_id' =>  $deal['user_id'],

        ]);

        $add->save();

        $where['orderid']=$deal['orderid'];

        $order=new BydShopOrder();

        $pid=$order->isUpdate(true,$where)->save(['state'=>'9']);
//   if($pid)
//        {
//          $res=\app\admin\model\BydShopOrder::where($where)->update(['returnstate'=>$oldstate],['orderid'=>$deal['orderid']]);
//        }
        if($pid){
            $this->success(__('请求成功'));
            return $deal;
        }else{
            $this->error(__('请求失败'));
            return null;
        }

    }

    /**

     * 待支付--修改地址
     * @param integer $id ` '订单的id',
     * @param integer $addressid ` '地址id',

     * id  订单id

     * addressid 地址id

     */

    public function editaddress(){

        $data = $this->request->request('');

        $user = BydShopOrder::get($data['id']);

        $user->addressid     =$data['addressid'];

        $user->save();

        if($user){
            $this->success(__('请求成功'));
            return $user;
        }else{
            $this->error(__('请求失败'));
            return null;
        }

    }





    /**

     * 带收货--确认收货

     */

    public function sureorder(){

        $data = $this->request->request('');

        $user = BydShopOrder::get($data['id']);
       if($user['score']==0){
           $user->state     =3;

       }else{
           $user->state     =4;
       }

        $user->oktime     =time()+86400*7;
        $user->save();
//b3购买物品返回百分之50%
        $userbbs=\app\api\model\BydUser::find($user['user_id']);

        if($userbbs['bbs']==3 && $user['price']>100000){
            $addbbs=new BydDispro();
            $addbbs->data([
                'user_id'=>$user['user_id'],
                'pid'=>$user['user_id'],
                'cjprice'=>$user['price'],
                'level' => 3,
                'money' => 0,
                'state' => 1,
                'type' => 0,
                'tixian' => 0,
                'order_id' => $user['orderid'],
                'price' => $user['price']*0.5
            ]);
            $addbbs->save();
        }

        if($user){
            $order=BydShopOrder::where('id',$data['id'])->find();
//
//            if(!empty($order['yyid'])){
//
//                //预约订单设计
//                $orderedit=\app\admin\model\BydDesignerMake::where('orderid',$order['yyid'])->update(['state'=>2]);//修改预约订单状态为完成
//                //如果有b端佣金则修改佣金为已完成
//                $yj=BydDispro::where('order_id',$order['orderid'])->find();
//                if(!empty($yj)){
//
//                    $yjedit=BydDispro::where('order_id',$order['orderid'])->update(['state'=>1]);
//                    $this->success(__('请求成功'));
//                }
//
//                $make = new \app\admin\model\BydDesignerMake();
//                $deswmake = \app\admin\model\BydDesignerMake::where('orderid', $order['yyid'])->find();
//                if ($deswmake) {
//                    $save = $make->where('worderid', $order['yyid'])->update(['wstate' => 1]);
//                    $user = BydDesigner::find($deswmake['des_id']);
//                    //设计师分佣
//                    $pro = BydDestri::where('user_id', $user['user_id'])->find();//查找团队关系表
//                    if ($pro['pid'] > 0) {
//                        ///////////
//                        //有父级
//                        if ($pro['pid'] == $pro['family']) {
//                            $fateherbbs = \app\admin\model\BydUser::find($pro['family']);//父亲身份
//                            $level = Db::name('BydIdentity')->where(['id' => $fateherbbs['des']])->find();
//
//                            if ($fateherbbs['bbs'] == 4) {
//                                //d1下级直接分佣
//                                $tc = $order['price'] * $level['myproduct'] / 100;//上级所得提成
//                                $add = new BydDispro();
//                                $add->data([
//                                    'cjprice' => $order['price'],
//                                    'level' => $pro['level'],
//                                    'pid' => $pro['family'],
//                                    'money' => 0,
//                                    'state' => 1,
//                                    'user_id' => $deswmake['user_id'],
//                                    'type' => 0,
//                                    'tixian' => 0,
//                                    'order_id' => $order['yyid'],
//                                    'price' => $tc
//                                ]);
//                                $add->save();
//                            } else {
//                                $tc = $order['price'] * $level['myproduct'] / 100;//上级所得提成
//                                $add = new BydDispro();
//                                $add->data([
//                                    'cjprice' => $order['price'],
//                                    'level' => $pro['level'],
//                                    'pid' => $pro['family'],
//                                    'money' => 0,
//                                    'state' => 1,
//                                    'user_id' => $deswmake['user_id'],
//                                    'type' => 0,
//                                    'tixian' => 0,
//                                    'order_id' => $order['yyid'],
//                                    'price' => $tc
//                                ]);
//                                $add->save();
//                                $findfa = BydDestri::where('user_id', $pro['family'])->find();
//                                if ($findfa['family'] > 0) {
//                                    $sgtc = $order['price'] * $level['sonproduct'] / 100;//上级所得提成
//                                    $adds = new BydDispro();
//                                    $adds->data([
//                                        'cjprice' => $order['price'],
//                                        'level' => $pro['level'],
//                                        'pid' => $findfa['family'],
//                                        'money' => 1,
//                                        'state' => 1,
//                                        'user_id' => $deswmake['user_id'],
//                                        'type' => 0,
//                                        'tixian' => 0,
//                                        'order_id' => $order['yyid'],
//                                        'price' => $sgtc
//                                    ]);
//                                    $adds->save();
//                                }
//                            }
//
//
//                        } else {
//                            $father = \app\admin\model\BydUser::where('id', $pro['pid'])->find();//查看父级身份
//                            if ($father['des'] > 0) {
//                                $level = \app\admin\model\BydIdentity::find($father['des']);
//                                $ftc = $order['price'] * $level['myproduct'] / 100;//上级所得提成
//                            }
////                    $ftc=$order['price']*$level['myproduct']/100;//上级所得提成
//                            $levelss = \app\admin\model\BydIdentity::find(4);
//                            $gfather = \app\admin\model\BydUser::where('id', $pro['family'])->find();//查看第一级别身份
//                            $levels = \app\admin\model\BydIdentity::find($gfather['des']);
//                            if ($gfather['des'] > 0 && $father['des'] == 0) {
//                                if ($gfather['des'] == 3) {
//                                    //bs身份
//                                    $gtc = $order['price'] * $levels['sonproduct'] / 100;//上级所得提成
//                                    $add = new BydDispro();
//                                    $add->data([
//                                        'cjprice' => $order['price'],
//                                        'level' => $pro['level'],
//                                        'pid' => $pro['family'],
//                                        'money' => 1,
//                                        'state' => 1,
//                                        'user_id' => $deswmake['user_id'],
//                                        'type' => 0,
//                                        'tixian' => 0,
//                                        'order_id' => $order['yyid'],
//                                        'price' => $gtc
//                                    ]);
//                                    $add->save();
//                                    $findfa = BydDestri::where('user_id', $pro['family'])->find();
//                                    if ($findfa['family'] > 0) {
//                                        $sgtc = $order['price'] * $levelss['sonproduct'] / 100;//上级所得提成
//                                        $adds = new BydDispro();
//                                        $adds->data([
//                                            'cjprice' => $order['price'],
//                                            'level' => $pro['level'],
//                                            'pid' => $findfa['family'],
//                                            'money' => 1,
//                                            'state' => 1,
//                                            'user_id' => $deswmake['user_id'],
//                                            'type' => 0,
//                                            'tixian' => 0,
//                                            'order_id' => $order['yyid'],
//                                            'price' => $sgtc
//                                        ]);
//                                        $adds->save();
//                                    }
//                                } else {
//                                    //b1
//                                    $gtc = $order['price'] * $levels['sonproduct'] / 100;//上级所得提成
//                                    $add = new BydDispro();
//                                    $add->data([
//                                        'cjprice' => $order['price'],
//                                        'level' => $pro['level'],
//                                        'pid' => $pro['family'],
//                                        'money' => 1,
//                                        'state' => 1,
//                                        'user_id' => $deswmake['user_id'],
//                                        'type' => 0,
//                                        'tixian' => 0,
//                                        'order_id' => $order['yyid'],
//                                        'price' => $gtc
//                                    ]);
//                                    $add->save();
//
//                                }
//
//                            } elseif ($gfather['des'] == 2 && $father['des'] > 0) {
//                                //bs身份
//                                $gtc = $order['price'] * $levels['sonproduct'] / 100;//上级所得提成
//                                $add = new BydDispro();
//                                $add->data([
//                                    'cjprice' => $order['price'],
//                                    'level' => $pro['level'],
//                                    'pid' => $pro['family'],
//                                    'money' => 1,
//                                    'state' => 1,
//                                    'user_id' => $deswmake['user_id'],
//                                    'type' => 0,
//                                    'tixian' => 0,
//                                    'order_id' => $order['yyid'],
//                                    'price' => $gtc
//                                ]);
//                                $add->save();
//                                $adds = new BydDispro();
//                                $adds->data([
//                                    'cjprice' => $order['price'],
//                                    'level' => $pro['level'],
//                                    'pid' => $pro['pid'],
//                                    'money' => 0,
//
//                                    'state' => 1,
//
//                                    'user_id' => $deswmake['user_id'],
//
//                                    'type' => 0,
//
//                                    'tixian' => 0,
//
//                                    'order_id' => $order['yyid'],
//
//                                    'price' => $ftc
//
//                                ]);
//
//                                $adds->save();
//                            } else {
//                                $add = new BydDispro();
//                                $add->data([
//                                    'cjprice' => $order['price'],
//                                    'level' => $pro['level'],
//                                    'pid' => $pro['pid'],
//                                    'money' => 0,
//                                    'state' => 1,
//                                    'user_id' => $deswmake['user_id'],
//                                    'type' => 0,
//                                    'tixian' => 0,
//                                    'order_id' => $order['yyid'],
//                                    'price' => $ftc
//                                ]);
//                                $add->save();
//                            }
//                        }
//
//                    }else{
//
//                        $fateherbbs = \app\admin\model\BydUser::find($pro['user_id']);//父亲身份
//                        $level = Db::name('BydIdentity')->where(['id' => $fateherbbs['des']])->find();
//
//                        if ($fateherbbs['des'] == 4) {
//                            $desmake=\app\admin\model\BydDesignerMake::where('orderid',$order['yyid'])->find();//找到该订单
//                            $desuser=BydDesigner::find($desmake['des_id']);
//                            $build=SoleBuilding::where('id',$desmake['bid'])->find();
//                           // print_r($desuser);die;
////                            print_r($build);die;
//                            //print_r($desmake['des_id']);die;
//                            if(!empty($build) && $build['sign_did']==$desuser['user_id']){
//
//                                $tc = $order['price'] * $level['myproducts'] / 100;//上级所得提成(楼盘设计师下得分佣)
//
//                            }else{
//                                $tc = $order['price'] * $level['myproduct'] / 100;//上级所得提成(普通设计师分佣)
//                            }
//                            //d1下级直接分佣
//                            $add = new BydDispro();
//                            $add->data([
//                                'cjprice' => $order['price'],
//                                'level' => $pro['level'],
//                                'pid' => $pro['user_id'],
//                                'money' => 0,
//                                'state' => 1,
//                                'user_id' => $deswmake['user_id'],
//                                'type' => 0,
//                                'tixian' => 0,
//                                'order_id' => $order['yyid'],
//                                'price' => $tc
//                            ]);
//                            $add->save();
//
//                        }elseif($fateherbbs['des'] == 3){
//                            $levels = Db::name('BydIdentity')->where(['id' => 3])->find();
//                            $tc = $order['price'] * $levels['myproduct'] / 100;//上级所得提成
//                            $add = new BydDispro();
//                            $add->data([
//                                'cjprice' => $order['price'],
//                                'level' => $pro['level'],
//                                'pid' => $pro['user_id'],
//                                'money' => 0,
//                                'state' => 1,
//                                'user_id' => $deswmake['user_id'],
//                                'type' => 0,
//                                'tixian' => 0,
//                                'order_id' => $order['yyid'],
//                                'price' => $tc
//                            ]);
//                            $add->save();
//                        }else{
//                            $levels = Db::name('BydIdentity')->where(['id' => 5])->find();
//                            $tc = $order['price'] * $levels['myproduct'] / 100;//上级所得提成
//                            $add = new BydDispro();
//                            $add->data([
//                                'cjprice' => $order['price'],
//                                'level' => $pro['level'],
//                                'pid' => $pro['user_id'],
//                                'money' => 0,
//                                'state' => 1,
//                                'user_id' => $deswmake['user_id'],
//                                'type' => 0,
//                                'tixian' => 0,
//                                'order_id' => $order['yyid'],
//                                'price' => $tc
//                            ]);
//                            $add->save();
//                        }
//                    }
//                }
//
//            }
//          $one=BydOrderSon::where('porderid',$order['orderid'])->sum('one');
//          $two=BydOrderSon::where('porderid',$order['orderid'])->sum('two');
//          $three=BydOrderSon::where('porderid',$order['orderid'])->sum('three');
//          if(!empty($order['one']) && !empty($order['two']) && !empty($order['three']) ){
//              //b3-b2-b1-c
//              $addone = new BydDispro();
//              $addone->data([
//                  'cjprice' => $order['price'],
//                  'level' => 1,
//                  'pid' => $order['one'],
//                  'money' => 0,
//                  'state' => 0,
//                  'user_id' => $order['user_id'],
//                  'type' => 0,
//                  'tixian' => 0,
//                  'order_id' => $order['orderid'],
//                  'price' => $one
//              ]);
//              $addone->save();
//              $addtwo = new BydDispro();
//              $addtwo->data([
//                  'cjprice' => $order['price'],
//                  'level' => 2,
//                  'pid' => $order['two'],
//                  'money' => 0,
//                  'state' => 0,
//                  'user_id' => $order['user_id'],
//                  'type' => 0,
//                  'tixian' => 0,
//                  'order_id' => $order['orderid'],
//                  'price' => $two
//              ]);
//              $addtwo->save();
//              $addthree = new BydDispro();
//              $addthree->data([
//                  'cjprice' => $order['price'],
//                  'level' => 3,
//                  'pid' => $order['three'],
//                  'money' => 0,
//                  'state' => 0,
//                  'user_id' => $order['user_id'],
//                  'type' => 0,
//                  'tixian' => 0,
//                  'order_id' => $order['orderid'],
//                  'price' => $three
//              ]);
//              $addthree->save();
//          }elseif(empty($order['one']) && !empty($order['two']) && !empty($order['three']) ){
//  //b3-b2-c
//              $addtwo = new BydDispro();
//              $addtwo->data([
//                  'cjprice' => $order['price'],
//                  'level' => 2,
//                  'pid' => $order['two'],
//                  'money' => 0,
//                  'state' => 0,
//                  'user_id' => $order['user_id'],
//                  'type' => 0,
//                  'tixian' => 0,
//                  'order_id' => $order['orderid'],
//                  'price' => $two+$one
//              ]);
//              $addtwo->save();
//              $addthree = new BydDispro();
//              $addthree->data([
//                  'cjprice' => $order['price'],
//                  'level' => 3,
//                  'pid' => $order['three'],
//                  'money' => 0,
//                  'state' => 0,
//                  'user_id' => $order['user_id'],
//                  'type' => 0,
//                  'tixian' => 0,
//                  'order_id' => $order['orderid'],
//                  'price' => $three
//              ]);
//              $addthree->save();
//          }elseif(empty($order['one']) && empty($order['two']) && !empty($order['three']) ){
//              //b3-c
//              $addthree = new BydDispro();
//              $addthree->data([
//                  'cjprice' => $order['price'],
//                  'level' => 3,
//                  'pid' => $order['three'],
//                  'money' => 0,
//                  'state' => 0,
//                  'user_id' => $order['user_id'],
//                  'type' => 0,
//                  'tixian' => 0,
//                  'order_id' => $order['orderid'],
//                  'price' => $three+$two+$one
//              ]);
//              $addthree->save();
//          }elseif(empty($order['one']) && !empty($order['two']) && empty($order['three']) ){
//              //b2-c
//              $addtwo = new BydDispro();
//              $addtwo->data([
//                  'cjprice' => $order['price'],
//                  'level' => 2,
//                  'pid' => $order['two'],
//                  'money' => 0,
//                  'state' => 0,
//                  'user_id' => $order['user_id'],
//                  'type' => 0,
//                  'tixian' => 0,
//                  'order_id' => $order['orderid'],
//                  'price' => $two+$one
//              ]);
//              $addtwo->save();
//          }elseif(!empty($order['one']) && empty($order['two']) && empty($order['three'])){
//              //b1-c
//              $addone = new BydDispro();
//              $addone->data([
//                  'cjprice' => $order['price'],
//                  'level' => 1,
//                  'pid' => $order['one'],
//                  'money' => 0,
//                  'state' => 0,
//                  'user_id' => $order['user_id'],
//                  'type' => 0,
//                  'tixian' => 0,
//                  'order_id' => $order['orderid'],
//                  'price' => $one
//              ]);
//              $addone->save();
//          }elseif (!empty($order['one']) && !empty($order['two']) && empty($order['three'])){
////b2-b1-c
//              $addtwo = new BydDispro();
//              $addtwo->data([
//                  'cjprice' => $order['price'],
//                  'level' => 2,
//                  'pid' => $order['two'],
//                  'money' => 0,
//                  'state' => 0,
//                  'user_id' => $order['user_id'],
//                  'type' => 0,
//                  'tixian' => 0,
//                  'order_id' => $order['orderid'],
//                  'price' => $two
//              ]);
//              $addtwo->save();
//              $addone = new BydDispro();
//              $addone->data([
//                  'cjprice' => $order['price'],
//                  'level' => 1,
//                  'pid' => $order['one'],
//                  'money' => 0,
//                  'state' => 0,
//                  'user_id' => $order['user_id'],
//                  'type' => 0,
//                  'tixian' => 0,
//                  'order_id' => $order['orderid'],
//                  'price' => $one
//              ]);
//              $addone->save();
//          }elseif (!empty($order['one']) && empty($order['two']) && !empty($order['three'])){
////b3-b1-c
//              $addone = new BydDispro();
//              $addone->data([
//                  'cjprice' => $order['price'],
//                  'level' => 1,
//                  'pid' => $order['one'],
//                  'money' => 0,
//                  'state' => 0,
//                  'user_id' => $order['user_id'],
//                  'type' => 0,
//                  'tixian' => 0,
//                  'order_id' => $order['orderid'],
//                  'price' => $one
//              ]);
//              $addone->save();
//              $addthree = new BydDispro();
//              $addthree->data([
//                  'cjprice' => $order['price'],
//                  'level' => 3,
//                  'pid' => $order['three'],
//                  'money' => 0,
//                  'state' => 0,
//                  'user_id' => $order['user_id'],
//                  'type' => 0,
//                  'tixian' => 0,
//                  'order_id' => $order['orderid'],
//                  'price' => $three+$two
//              ]);
//              $addthree->save();
//          }
          $where['user_id']=['eq',$order['user_id']];
//          $where['one']=['eq',$order['one']];
//          $where['two']=['eq',$order['two']];
//          $where['three']=['eq',$order['three']];
          $dele=Temrela::where($where)->delete();
          $updarr=BydDispro::where('order_id',$order['orderid'])->update(['state'=>1]);
          $updarrs=BydDispro::where('order_id',$order['yyid'])->update(['state'=>1]);
          //$dele=Temrela::where('user_id',$order['id'])->where('one',$order['one'])->where('two',$order['two'])->where('three',$order['three'])->delete();
            $this->success(__('修改成功'));
        }else{
            $this->error('修改失败');
        }

    }
    /**
     * 定金
     * @param integer $orderid ` '订单id',
     */
    public function dingj(){
        $data = $this->request->request('');
        $find=\app\admin\model\BydDesignerMake::where('orderid',$data['orderid'])->find();
        if (empty($find))$this->error('订单不存在');
        $this->success(__('请求成功'),['status'=>$find]);
    }
    /**

     * 添加收藏
     * @param integer $type ` '0为商品1为视频',
     * @param integer $user_id` '用户id',
     * @param integer $shop_id` '商品id',
     * @param integer $viedo_id ` '视频id',
     *

     * type 0为商品1为视频

     * user_id 用户id

     * shop_id 商品id

     * viedo_id 视频id

     */

    public function addfollow(){

        $data = $this->request->request('');

        $add=\app\api\model\BydShop::addfollow($data);

        if($add==null){

            $this->error('添加失败');

        }else{

            $this->success(__('添加成功'));

        }

    }



/**

 * 查看物流
 * @param integer $id ` '订单id',

 * id  订单id

 */

public function lookexpress(){

    $data = $this->request->request('');

    $arr=\app\api\model\BydShop::lookexpress($data);
//print_r($arr['message']);
    //print_r($arr['message']);die;
    if($arr['message']!='ok'){
        $order=BydShopOrder::find($data['id']);
//        print_r($order['orderid']);die;
        $news=BydSdexpress::where('orderid',$order['orderid'])->order('id desc')->select();
        
        $arr['data']=$news;
        $this->success(__('请求成功'),['status'=>$arr]);
    }else{
        $this->success(__('请求成功'),['status'=>$arr]);
    }

    // var_dump($pd);die;

    if($arr==null){
        $this->error('请求失败');
    }else{
        $this->success(__('请求成功'),['status'=>$arr]);

    }

}

/**

 * 我的订单
 * @param integer $user_id ` '用户id',

 * user_id 用户id

 */

public function myorder(){

    //todo 删除多余订单
//    $orderLists = BydShopOrder::select();
//    foreach ($orderLists as $vals){
//        $son =  Db::table('fa_byd_order_son')->where('porderid',$vals['orderid'])->select();
//        if(empty($son)){
//            Db::table('fa_byd_shop_order')->where('id',$vals['id'])->delete();
//        }
//    }
    $data = $this->request->request('');

    $arr=BydShopOrder::where(['user_id'=>$data['user_id']])->order('id desc')->select();



    foreach ($arr as &$v){
        if($v['cuponsid']>0){
            $v['yhprice']=BydCupon::where('id',$v['cuponsid'])->find();
        }else{
            $v['yhprice']=0;
        }
        $v['cretime']=strtotime($v['create_at'])-86400;
        $v['dingjin']=\app\admin\model\BydDesignerMake::where('orderid',$v['yyid'])->field('price')->find();
        //$v['paytime']=BydDispro::where('order_id',$v['orderid'])->field('createtime')->find();
        $v['shop']= Db::table('fa_byd_shop_order')

            ->alias('o')

            ->join('fa_byd_order_son s','o.orderid = s.porderid')
            //->join('fa_byd_designer_make m','o.yyid = m.orderid')
            ->join('fa_byd_shop p','p.id = s.productid')

           ->where('o.orderid',$v['orderid'])

            ->field('o.orderid,o.state,o.price,p.simage,p.name,s.num,s.price as sonprice,p.id')

            ->select();

//        $where['id'] = array('in',$v['productid']);

//        $v['shop']=\app\admin\model\BydShop::where($where)->select();



    }



    if($arr){

        $this->success(__('请求成功'),['status'=>$arr]);

    }else{

        $this->error('暂无数据');

    }

}

    /**

     * 订单详情
     * @param integer $id ` '订单id',

     * id 订单id

     */

    public function myorderxq(){

        $data = $this->request->request('');

        $arr=BydShopOrder::where('orderid',$data['id'])->find();

        $arr['shop']=BydShopCart::where('id','in',$arr['productid'])->select();

        if($arr){

            $this->success(__('请求成功'),['status'=>$arr]);

        }else{

            $this->error('暂无数据');

        }

    }
    /**
     * 申请售后
     * @param integer $user_id ` '用户id',
     * @param integer $type ` '为退货1为换货',
     * @param integer $orderid ` '订单号',
     * @param integer $shopid ` '商品id组',
     * @param integer $num` '数量',
     * @param integer $tuik_ly ` '退款理由',
     * @param integer $image ` '退款照片',
     *
     * user_id
     * type 0为退货1为换货
     * orderid 订单号
     * shopid 商品id组
     * num 数量
     * tuik_ly 退款理由
     * image  退款照片
     */
public function sqorder(){

    $data = $this->request->request('');
    $add = new BydOrderTuishop();
    if(empty($data['shopid'])) $this->error('商品参数不全');
    $shop=explode(",", $data['shopid']);
    foreach ($shop as $v){
        $shopfind=BydOrderSon::find($v);
        if($shopfind){
            $add->data([
                'price'  =>$shopfind['price'],
                'user_id'=>$data['user_id'],
                'num'=>$data['num'],
                'orderid'  =>$data['orderid'],
                'productname'=>$shopfind['productname'],
                'address'=>$shopfind['address'],
                'state'=>$data['type'],
                'productid'=>$shopfind['productid'],
                'specidsize'=>$shopfind['specidsize'],
                'special'=>$shopfind['special'],
                'good_image'=>$shopfind['good_image'],
            ]);
            $add->save();
        }
    }
if($data['type']==0){
   //退货
    $tuiprice=BydOrderTuishop::where('orderid',$data['orderid'])->where('state',0)->sum('price');
    $arr=[
        'state'=>10,//订单状态
        //'tuishopid'=>$data['shopid'],//退款货物id
        'tuik_ly'=>$data['tuik_ly'],//退款理由
        'image'=>$data['image'],//退款照片
        'tuiprice'=>$tuiprice,
        'sqtime'=>time(),
    ];
    $orderstate=BydShopOrder::where('orderid',$data['orderid'])->update($arr);//修改订单的状态
    if($orderstate){
        \think\Cache::set('name',1,3600);
        $this->success(__('申请成功'));
    }else{
        $this->error(__('申请失败'));
    }
}else{
    //换货
    $arr=[
        'state'=>13,//订单状态
        //'tuishopid'=>$data['shopid'],//退款货物id
        'tuik_ly'=>$data['tuik_ly'],//退款理由
        'image'=>$data['image'],//退款照片
        'sqtime'=>time(),
    ];
    $orderstate=BydShopOrder::where('orderid',$data['orderid'])->update($arr);//修改订单的状态
    if($orderstate){
        \think\Cache::set('name',1,3600);
        $this->success(__('申请成功'));
    }else{
        $this->error(__('申请失败'));
    }
}
}
    /**

     * 申请退款
     * @param integer $type ` '0为待发货的退款1为已完成的退款',
     * @param integer $orderid` '订单号',
     * @param integer $user_id ` '用户id',
     * @param integer $content ` '退款原因',
     *

     * type  0为待发货的退款1为已完成的退款

     * orderid 订单号

     * user_id 申请用户

     * content 退款原因

     */

public function ordertui(){

    $data = $this->request->request('');
    $oldstate = -1;
//    if($data['type']==0){
        $ordertui=BydOrderTui::where('orderid',$data['orderid'])->where('state',0)->find();
        if(!empty($ordertui)) $this->error('请勿重复提交');
        $order=BydShopOrder::where('orderid',$data['orderid'])->find();
        $oldstate = $order['state'];
        $add = new BydOrderTui();
        $add->data([
            'price'  =>$order['price'],
            'orderid'  =>$data['orderid'],
            'tuik_ly' =>  $data['content'],
            'image' =>  $data['image'],
            'user_id' =>  $data['user_id'],
        ]);
        $add->save();
        $where['orderid']=$data['orderid'];
        $order=new BydShopOrder();
        $pid=$order->isUpdate(true,$where)->save(['state'=>'5']);
//    }else{
//        $order=BydShopOrder::where('orderid',$data['orderid'])->find();
//$oldstate = $order['state'];
//        $where['orderid']=$data['orderid'];
//        $order=new BydShopOrder();
//        $pid=$order->isUpdate(true,$where)->save(['state'=>'5','tuik_ly'=>$data['content'],'image'=>$data['image']]);
//    }



    if($pid){

          $res=\app\admin\model\BydShopOrder::update(['returnstate'=>$oldstate],['orderid'=>$data['orderid']]);
        \think\Cache::set('tuit',1,3600);
        $this->success(__('请求成功'));

    }else{

        $this->error('请求失败');

    }

}

    /**

     * 退款理由渲染

     */

    public function ordertuiset(){

        $arr=BydOrderTui::select();

        if($arr){

            $this->success(__('请求成功'),['status'=>$arr]);

        }else{

            $this->error('暂无数据');

        }

    }

    /**

     * 获取accesstoken

     */

    public function getAccessToken()

    {

        $appId = 'wx00e9e5b843259a9d';

        $secretId ='5a47f8a3b97773614c77da7900a896a3';

        $accessUrl = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET';

        // $url = sprintf($accessUrl,$appId,$secretId);

        $url='https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx00e9e5b843259a9d&secret=5a47f8a3b97773614c77da7900a896a3';

        //print_r($url);die;

        $result =$this->https_request($url);

        //$result = $this->https_request($url);

        $Result = json_decode($result, true);

        return $Result['access_token'];

        // return $Result;



    }

    #curl请求

    public function https_request($url,$data = null){

        if(function_exists('curl_init')){



            $curl = curl_init();

            curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);

            curl_setopt($curl, CURLOPT_URL, $url);

            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);

            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);

            curl_setopt($curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);

            curl_setopt($curl, CURLOPT_FOLLOWLOCATION,1);

            if (!empty($data)){

                curl_setopt($curl, CURLOPT_POST, 1);

                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);

            }

            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

            $output = curl_exec($curl);



            curl_close($curl);

            return $output;

        }else{

            return false;

        }

    }





/**

 * 智慧薪用户注册

 */

//public function zhxtoken(){

//    $url='https://api.xinrenxinshi.com/authorize/oauth/token?grant_type=client_credentials&client_secret=Es2yPo_BG8a6uzBlWgvb&client_id=appBDrOGcHXWrPlnG3YFmpQs8p62MYYS';

//    //print_r($url);die;

//    $result =$this->https_request($url);

//    //$result = $this->https_request($url);

//    $Result = json_decode($result, true);

//    print_r($Result);

//    return $Result['access_token'];

//}

    /**

     * 智慧薪用户注册

     */

 public function userinset(){

     $time=time();

     $orderNo = date('YmdHis',$time) . round(1000,9999);

     $arr = [

         'version'       =>'1.0',

         'current_time'  =>(string) date('YmdHis',$time),

         'mch_id'        => '3995963256974868480',

         'nonce_number'  => (string)$orderNo,

         'request_number'=> (string)$orderNo,

         'tel'           =>'17683154674',

     ];



     $url = 'http://zhxapiv1.52zeiduo.com/api/open/register';

     $str    = $this->ToUrlParams($arr);

     $sign   = $this->sign($str);//签名

     $arr['key_sign'] = $sign;



     $client = new \GuzzleHttp\Client(['verify'=>false]);

     $header = [

         'Content-Type'  => 'application/json; charset=utf-8',

     ];

     $ret = $client->request('POST',$url,['json' => $arr,'headers'=>$header]);

     $ret = json_decode($ret->getBody()->getContents(),1);

     print_r( $ret );die();



//     $arr['key_sign'] = $sign;

//

//     $data = json_encode($arr);

//     $header = ['Content-type:application/json;charset=utf-8'];

//     $ret = $this->httpss_request( $url, 'post', $data,$header);

//     print_r( $ret );die();



 }

    private function ToUrlParams( $data ) {

        ksort($data);

        $buff = "";

        foreach ($data as $k => $v)

        {

            if($k != "sign" && $v != "" && !is_array($v)){

                $buff .= $k . "=" . $v . "&";

            }

        }



        $buff = trim($buff, "&");

        return $buff;

    }

    /**

     * 智慧薪签名算法

     */

public function sign($data){

    $arr=$data."&key=9e9655d7dca84b32991064e510332243";

    $key=strtoupper(md5($arr));

    return $key;

}

/**

 * 智慧薪上传文件

 */

public function upfile(){

    $mch_id = '3995963256974868480';

    $type   = '01';

    $value  = '3996330624645332992';

    $path = getcwd() .'/'.'photo/6/61/2.jpeg';

    $body = [

        [ 'name'=>'image',

            'contents'=>fopen( $path, 'rb'),

            'headers' => ['Content-Type'  => 'multipart/form-data; charset=utf-8',],

        ]

    ];

    $url = "http://zhxapiv1.52zeiduo.com/api/open/uploadfile?mch_id={$mch_id}&type={$type}&value={$value}";



    $client = new \GuzzleHttp\Client(['verify'=>false]);

    $header = [

        'Content-Type'  => 'multipart/form-data; charset=utf-8',

    ];

    $ret = $client->request('POST',$url,['multipart' => $body]);

    $ret = json_decode($ret->getBody()->getContents(),1);

}

/**

 * 智慧薪实名认证

 */

public function userrz(){

    $img1 = '1QxtHLkLU8dvGf+0leRi3dK7dY9ptG97lWMRL4cAcnYx2DHVx0ElVKKOo/FSUST1nYqz6SXudZrLbpo/iAMt3g==';

    $img2 = 'bkvwTumqxAAd+fH60r0J4g1ScDt8TYDP1f+Bkt4gqrKIaNEJxkxmiWu5/Y0q8JRMnYqz6SXudZrLbpo/iAMt3g==';

    $time = time();

    $orderNo = date('YmdHis',$time) . round(1000,9999);

    $data = [

        'version'           => '1.0',

        'current_time'      => date('YmdHis',$time),

        'mch_id'            => '3995963256974868480',

        'nonce_number'      => (string) $orderNo,

        'request_number'    => (string) $orderNo,

        'freelance_id'      => '3996330624645332992',

        'name'              => '张三',

        'mobile'            => '18038129688',

        'card_number'       => '429001199010063214',

        'card_positive_img' => $img1,

        'card_negative_img' => $img2,

        'bank_number'       => '4568153015369565',

        'bank_name'         => '招商银行',

    ];

    $str    = $this->ToUrlParams( $data );

    $sign   = $this->sign($str);//签名



    $url = 'http://zhxapiv1.52zeiduo.com/api/open/appraisalauthority';

    $data['key_sign'] = $sign;

    $client = new \GuzzleHttp\Client(['verify'=>false]);

    $header = [

        'Content-Type'  => 'application/json; charset=utf-8',

    ];

    $ret = $client->request('POST',$url,['json' => $data,'headers'=>$header]);

    $ret = json_decode($ret->getBody()->getContents(),1);

    print_r( $ret );die();

}

/**

 * 微信提现

 */

public function wechattx(){

    $shop=new \app\api\model\BydShop();

    $find=$shop->transfer(1);

    print_r($find);

}

    /**

     * 优惠卷渲染

     */

    public function yhq(){

        $arr=BydCupon::select();

        if($arr){

            $this->success(__('请求成功'),['status'=>$arr]);

        }else{

            $this->error('暂无数据');

        }

    }

    /**

     * 领取优惠劵
     * @param integer $user_id ` '用户id',
     * @param integer $cid` '优惠劵id',
     * @param integer $num ` '数量',
     *

     * user_id

     * cid 优惠劵id

     * num  数量

     */

    public function lqcuopon(){

        $data = $this->request->request('');

        $add = new BydMycupon();

        $add->data([

            'user_id'  => $data['user_id'],

            'cupon' =>  $data['cid'],

            'num' =>   $data['num'],

            'price' =>  $data['price'],

        ]);

        $add->save();

        if($add){

            $cupon=new BydCupon();

            $sit=$cupon->where('id',$data['cid'])->setDec('num',1);

            $this->success(__('领取成功'));

        }else{

            $this->error('领取失败');

        }

    }

/**

 * 我的优惠劵
 * @param integer $user_id ` '用户id',

 * user_id 用户id

 */

public function mycupon(){

    $data = $this->request->request('');

     $arr=BydMycupon::where('user_id',$data['user_id'])->select();

     foreach ($arr as &$v){

         $v['cupons']=BydCupon::where('id',$v['cupon'])->find();

     }

     if($arr){

         $this->success(__('请求成功'),['status'=>$arr]);

     }else{

         $this->error('暂无数据');

     }

}
/**
 * 用户注册
 * @param integer $user_id ` '用户id',
 * @param integer $phone ` '电话号码',

 *
 */
public function myreg(){
    $data = $this->request->request('');

    if ( empty($data['phone']) || !is_numeric($data['phone']) || empty($data['user_id']) || !is_numeric($data['user_id']) ) {
        return json(['code'=>0,'msg'=>'参数错误']);
    }
    $qq =preg_match_all("/^1[3456789]\d{9}$/", $data['phone'], $mobiles);
    if ( !$qq ) $this->error(__('请输入正确的电话号码'));
    //用户表
    $user = \app\api\model\BydUser::find($data['user_id']);
    if(!empty($user['freelance_id']))$this->success(__('已完成手机号注册'));
    if (empty($user))return json(['code'=>0,'msg'=>'用户不存在']);
   // if(!empty($user['freelance_id']))return json(['code'=>0,'msg'=>'请勿重复注册']);
    $zhx=new Zhihuixin();
    $ret=$zhx->myreg($data);

    if($ret['return_code']!=0000){
        $this->error('注册失败',['data'=>$ret['return_msg']]);
    }
    $user=\app\admin\model\BydUser::where('id',$data['user_id'])->update(['freelance_id'=>$ret['freelance_id'],'mobile'=>$data['phone']]);
    if ($user){
        $this->success(__('注册成功'));
    }else{
        $this->error(__('服务器繁忙，请稍后再试'));
    }
}
/**
 * 用户上传身份照片
 * @param integer $type ` '0为正面1为反面',
 * @param integer $user_id ` '用户id',
 * @param integer $image` '照片路径',
 * type 0为正面1为反面
 * user_id
 * image
 */
public function userupload(){
    $data = $this->request->request('');
    if(empty($data['user_id']) || !is_numeric($data['user_id']))  return json(['code'=>0,'msg'=>'参数错误']);
    $user = \app\api\model\BydUser::find($data['user_id']);
    if (empty($user))return json(['code'=>0,'msg'=>'用户不存在']);
    if(empty($user['freelance_id']))return json(['code'=>0,'msg'=>'用户未注册智慧平台']);
    $data['freelance_id']=$user['freelance_id'];
    if($data['type']==0){
        //if(!file_exists($data['image']))return ['return_code'=>400,'return_msg'=>'图片路径不正确'];
        $userzimage = \app\api\model\BydUser::where('id',$data['user_id'])->update(['zidcard'=>$data['image']]);
//        if($userzimage){
//            $data['image']=$user['zidcard'];
//        }else{
//            return json(['code'=>04,'msg'=>'照片上传失败']);
//        }
    }else{
        //if(!file_exists($user['image']))return ['return_code'=>400,'return_msg'=>'图片路径不正确'];
        $userzimage = \app\api\model\BydUser::where('id',$data['user_id'])->update(['fidcard'=>$data['image']]);
//        if($userzimage){
//            $data['image']=$user['fidcard'];
//        }else{
//            return json(['code'=>04,'msg'=>'照片上传失败']);
//        }
    }
    $zhx=new Zhihuixin();
    $ret=$zhx->useruoloud($data);
    if($ret['return_code']!=0000){
        $this->error('上传失败',['data'=>$ret['return_msg']]);
    }
    if($data['type']==0){
        $users=\app\admin\model\BydUser::where('id',$data['user_id'])->update(['zupload'=>$ret['upload_file']]);
    }else{
        $users=\app\admin\model\BydUser::where('id',$data['user_id'])->update(['fupload'=>$ret['upload_file']]);
    }
    if($users){
        $this->success(__('上传成功'));
    }else{
        $this->error(__('服务器繁忙，请稍后再试'));
    }
}
/**
 * 实名认证
 * @param integer $user_id ` '用户id',
 * user_id
 */
public function realname(){
    $data = $this->request->request('');
    $user = \app\api\model\BydUser::find($data['user_id']);
  ;
    if(empty($user) || empty($user['realname']) || empty($user['zupload']) || empty($user['fupload']) || empty($user['bankid']) || empty($user['bankname']))  return json(['code'=>0,'msg'=>'用户参数不齐全']);
    $zhx=new Zhihuixin();
    $ret=$zhx->realname($user);

    if($ret['return_code']!=0000){
        $this->error('认证失败',['data'=>$ret['return_msg']]);
    }

    if($ret['result_msg']=="实名认证成功" ){
        $this->success(__('认证成功'));
    }else{
        $this->success(__('认证失败'),['data'=>$ret['result_msg']]);
    }

}
/**
 * 查询是否签约成功
 * @param integer $user_id ` '用户id',
 * user_id
 */
public function querysuccess(){
    $data = $this->request->request('');
    $user = \app\api\model\BydUser::find($data['user_id']);

    if(empty($user)  || empty($user['freelance_id'])) return json(['code'=>0,'msg'=>'用户参数不齐全']);
    $zhx=new Zhihuixin();
    $ret=$zhx->querysuccess($user);
    if($ret['return_code']!=0000){
        $this->error('签约失败',['data'=>$ret['return_msg']]);
    }
    if($ret['signauth_status']==3){
        $this->success('已签约授权',null,200);
    }elseif($ret['signauth_status']==1){
        $this->success(__('未签约授权'));
    }
}
    /**
     * 用户信息查询
     * @param integer $user_id ` '用户id',
     * user_id
     */
    public function userinfo(){
        $data = $this->request->request('');
        $user = \app\api\model\BydUser::find($data['user_id']);

        if(empty($user)  || empty($user['freelance_id'])) return json(['code'=>0,'msg'=>'用户参数不齐全']);
        $zhx=new Zhihuixin();

        $ret=$zhx->userinfo($user);

        if($ret['return_code']!=0000){
            $this->error('请求失败',['data'=>$ret['return_msg']]);
        }
        $this->success(__('请求成功'),['status'=>$ret]);
    }
    /**
     * 查询订单信息
     * @param integer $user_id ` '用户id',
     * @param integer $order_on ` '签约的订单号',
     */
    public function countsinfo(){
        $data = $this->request->request('');
        $user = \app\api\model\BydUser::find($data['user_id']);
        $user['order_no']=$data['order_on'];
        if(empty($user)  || empty($user['freelance_id'])) return json(['code'=>0,'msg'=>'用户参数不齐全']);
        $zhx=new Zhihuixin();

        $ret=$zhx->countsinfo($user);

        if($ret['return_code']!=0000){
            $this->error('请求失败',['data'=>$ret['return_msg']]);
        }
        $this->success(__('请求成功'),['status'=>$ret]);
    }
    /**
     * 用户领取任务
     * @param integer $user_id ` '用户id',
     */
    public function gettask(){
        $data = $this->request->request('');
        $user = \app\api\model\BydUser::find($data['user_id']);

        if(empty($user)  || empty($user['freelance_id'])) return json(['code'=>0,'msg'=>'用户参数不齐全']);
        $zhx=new Zhihuixin();
        $ret=$zhx->gettask($user);
        if($ret['return_code']!=0000){
            $this->error('领取失败',['data'=>$ret['return_msg']]);
        }
        $edit=\app\admin\model\BydUser::where('id',$data['user_id'])->update(['rw'=>1]);
        $this->success(__('领取成功'),['data'=>$ret]);
    }
    /**
     * 查看签约授权进度
     * @param integer $user_id ` '用户id',
     */
    public function taskstatus(){
        $data = $this->request->request('');
        $user = \app\api\model\BydUser::find($data['user_id']);

        if(empty($user)  || empty($user['freelance_id'])) return json(['code'=>0,'msg'=>'用户参数不齐全']);
        $zhx=new Zhihuixin();
        $ret=$zhx->taskstatus($user);

        if($ret['return_code']!=0000){
            $this->error('请求失败',['data'=>$ret['return_msg']]);
        }
        $this->success(__('请求成功'),['data'=>$ret]);
    }
    /**
     * 签约授权
     * @param integer $user_id ` '用户id',
     * user_id
     */
    public function contract(){
        $data = $this->request->request('');
        $user = \app\api\model\BydUser::find($data['user_id']);

        if(empty($user)  || empty($user['freelance_id'])) return json(['code'=>0,'msg'=>'用户参数不齐全']);
        $zhx=new Zhihuixin();
        $ret=$zhx->contract($user);
        if($ret['return_code']!=0000){
            $this->error('签约失败',['data'=>$ret['return_msg']]);
        }
        $this->success(__('认证成功'),['data'=>$ret['signurl']]);
    }
    /**
     * 确认支付
     * @param integer $user_id ` '用户id',
     * @param integer $freelance_id` '智慧薪标识符',
     */
    public function tage(){
        $data = $this->request->request('');
        $user = \app\api\model\BydUser::find($data['user_id']);

        if(empty($user)  || empty($user['freelance_id'])) return json(['code'=>0,'msg'=>'用户参数不齐全']);
        $zhx=new Zhihuixin();
        $ret=$zhx->tage($user);
        if($ret['return_code']!=0000){
            $this->error('请求失败',['data'=>$ret['return_msg']]);
        }
        $this->success(__('请求成功'),['data'=>$ret]);
    }

/**
 * 商城导航栏
 */
public function shopicon(){
    $arr=BydShopIcon::select();
    $this->success('请求成功',['data'=>$arr]);
}
/**
 * 限时抢购
 */
 public function timeshop(){
     $data = $this->request->request('');
     $time=time();
     $find=BydShopActivity::find(4);
     //$arr = explode(",", $find['shopid']);
     $arr=\app\api\model\BydShop::where('id','in',$find['shopid'])->select();
     $arrcupons=BydCupon::where('id','in',$find['cuponsid'])->where('switch',1)->where('endtime','>',time())->select();
     if($time>$find['endtime'])   $this->error('暂无数据');
     $this->success('请求成功',['data'=>$arr,'cupons'=>$arrcupons]);
 }
 /**
  * 删除订单
  * @param integer $orderid ` '订单id',
  */
 public function deleorder(){
     $data = $this->request->request('');
     if (empty($data['orderid'])) $this->error('订单编号不能为空');
     $order=BydShopOrder::where('orderid',$data['orderid'])->find();
     if (empty($order)) $this->error('订单不存在');
     $del=BydShopOrder::where('orderid',$data['orderid'])->delete();
//     $delfy=BydDispro::where('order_id',$data['orderid'])->delete();
     if($del){
         $this->success('删除成功');
     }else{
         $this->error('删除失败');
     }
 }
 /**
  * c端提交退换货的物流信息
  * @param integer $orderid ` '订单id',
  * @param integer $sqexpress ` '物流公司',
  * @param integer $sqexpressorder ` '物流单号',
  */
 public function sqexpress(){
     $data = $this->request->request('');
     if (empty($data['orderid']))$this->error('订单编号不能为空');
     $arr=[
         'sqexpress'=>$data['sqexpress'],
         'sqexpressorder'=>$data['sqexpressorder'],
     ];
     if(!empty($arr)){
         $update=BydShopOrder::where('orderid',$data['orderid'])->update($arr);
         if($update){
             $this->success('提交成功');
         }else{
             $this->error('提交失败');
         }
     }
 }
 /**
  * 申请报装
  * @param integer $orderid ` '订单id',
  * @param integer $shopid ` '商品id',
  * @param integer $userid ` '用户id',
  */
 public function sqlading()
 {
     $data = $this->request->request('');
     if(empty($data['shopid']))$this->error('申请报装商品不能为空');
     if(empty($data['userid']))$this->error('请登录');
     if(empty($data['orderid']))$this->error('订单号不正确');

     $add=new BydLoding();
     $add->data([
         'orderid'=>$data['orderid'],
         'shopid'=>$data['shopid'],
         'userid'=>$data['userid']
     ]);
     $add->save();
     if($add){
         $orderedit=BydShopOrder::where('orderid',$data['orderid'])->update(['state'=>16]);
         $this->success('提交成功,平台正在加急处理');
     }else{
         $this->error('提交失败');
     }
 }
 /**
  *安装完成
  * @param integer $orderid ` '订单id',
  */
 public function successloading(){
     $data = $this->request->request('');
     if(empty($data['orderid']))$this->error('订单号不正确');
     $edit=BydShopOrder::where('orderid',$data['orderid'])->update(['state'=>17]);
     $find=BydShopOrder::where('orderid',$data['orderid'])->find();

     if($find['twofw']==1){
         $user=$find['two'];
     }elseif($find['threefw']==1){
         $user=$find['three'];
     }else{
         $user=0;
     }

     $price=BydOrderSon::where('porderid',$data['orderid'])->sum('bz');
     $findsq=BydDispro::where('bz',1)->where('order_id',$find['orderid'])->find();
     if(empty($findsq)){
         $finduser=BydDispro::where('pid',$user)->where('order_id',$find['orderid'])->find();
         if(!empty($finduser)){
             $upup=BydDispro::where('id',$finduser['id'])->setInc('price',$price);
             $edit=BydDispro::where('id',$finduser['id'])->update(['bz'=>1]);
             if($upup){
                 $this->success('请求成功');
             }else{
                 $this->error('请求失败');
             }
         }else{
             $this->error('服务器繁忙');
         }
//         if($price>0){
//             $addthree = new BydDispro();
//             $addthree->data([
//                 'cjprice' => $find['price'],
//                 'level' => 0,
//                 'pid' => $user,
//                 'money' => 0,
//                 'state' => 1,
//                 'user_id' => $find['user_id'],
//                 'type' => 0,
//                 'tixian' => 0,
//                 'bz' => 1,
//                 'order_id' => $find['orderid'],
//                 'price' => $price
//             ]);
//             $addthree->save();
//             if($addthree){
//                 $this->success('请求成功');
//             }else{
//                 $this->error('请求失败');
//             }
//         }
     }


 }
 /**
  * 开关
  */
public function bzxq(){
    $data = $this->request->request('');
    $find=BydLoding::find($data['id']);
    if(empty($find))$this->error('暂无数据');
    $this->success('请求成功',['status'=>$find]);
}
/**
 *  取消售后
 * @param integer $orderid ` '订单id',
 */
public function xqsh(){
    $data = $this->request->request('');
    if(empty($data['orderid']))$this->error('订单号不能为空');
    $order=BydShopOrder::where('orderid',$data['orderid'])->find();
    if(empty($order))$this->error('订单号错误');
    $orderstate=BydShopOrder::where('orderid',$data['orderid'])->update(['state'=>4]);
    if($orderstate){
        $this->success('取消成功');
    }else{
        $this->error('取消失败');
    }
}
    /**
     * 检测B端用户协议是否到期
     * @param integer $user_id ` '用户id',
     */
    public function jc(){
        $data = $this->request->request('');
        $find=BydUserAg::where('user_id',$data['user_id'])->where('endtime','<',time())->find();
        if(empty($find))$this->error('暂无数据');
        $this->success('请求成功',['status'=>$find]);
    }
/**
 * 用户添加协议
 * @param integer $userid ` '用户id',
 * @param integer $title ` '楼盘名称',
 * @param integer $lpid ` '楼盘id',
 * @param integer $agid ` '协议id',
 */
public function userag(){
    $data = $this->request->request('');
    $title = $this->request->request('title');
    $lpid = $this->request->request('lpid');
    if($title){
        $data['title']=$title;
    }else{
        $data['title']='';
    }
    if($lpid){
        $data['lpid']=$lpid;
    }else{
        $data['lpid']=0;
    }

    if(empty($data['userid']))$this->error('请登录');
    $findsagment=BydAgreement::where('id',$data['agid'])->find();
    if(empty($findsagment))$this->error('参数错误');
     if( $findsagment['state']==7 || $findsagment['state']==12){
         $sf=BydUserSale::where('user_id',$data['userid'])->find();
         $realname=$sf['name'];
         $sfz=$sf['idcart'];
     }elseif ( $findsagment['state']==6){
         $sf=BydDesigner::where('user_id',$data['userid'])->find();
         $realname=$sf['username'];
         $sfz=$sf['idcart'];
     }else{
         $realname='无';
         $sfz='无';
     }

    if($data['agid']==48 || $data['agid']==49){
        if($data['agid']==48){
            //d端身份
            $des=BydDesigner::where('user_id',$data['userid'])->find();
            if(!empty($des)){
                $name=$des['username'].$des['idcart'];
                $onname=$des['username'];
            }else{
                $name='乙方';
                $onname='乙方';
            }

        }else{
            $bbs=\app\api\model\BydUser::where('id',$data['userid'])->find();
            $bbsreal=BydUserSale::where('user_id',$data['userid'])->find();
            if(!empty($des)){
                $name=$bbsreal['name'].$bbsreal['idcart'];
                $onname=$bbsreal['name'];
            }else{
                $name='乙方';
                $onname='乙方';
            }

        }
        $findag=BydAgreement::where('id',$data['agid'])->find();
//    if($findag['state']==0 || $findag['state']==0){
//
        $build=SoleBuilding::find($data['lpid']);
        $array=explode(",", $build['house_imgs']);;
        foreach ($array as $v){
            $image[]='https://bao.scwushen.com/'.$v;
        }
        $arr=$findag['content'];
        $startime= date ( 'Y-m-d' );
        $endtime=date ( 'Y-m-d' , strtotime ( '+364 day' ));
//        $star=date('Y-m-s',$startime);
        $arr=str_replace('{$name}',$name,$arr);
        $arr=str_replace('{$onname}',$onname,$arr);
        $arr=str_replace('{$address}',$build['address'],$arr);
        $arr=str_replace('{$bz}',$build['standard'],$arr);
        $arr=str_replace('{$time}',$build['trun_time'],$arr);
        $arr=str_replace('{$huxin}',$build['house_type'],$arr);
        $imagestring='';
        foreach ($image as $v){
            $imagestring.='<img src='.$v.'>';
        }
        $arr=str_replace('{$image}',$imagestring,$arr);
        $arr=str_replace('{$startime}',$startime,$arr);
        $arr=str_replace('{$endtime}',$endtime,$arr);
        $data['title']=$arr;
    }else{
        $startime=date ( 'Y-m-d' );//date ( 'Y-m-d' )
        $endtime=date ( 'Y-m-d' , strtotime ( '+364 day' ));
        $agment=BydAgreement::where('id',$data['agid'])->find();

//        $bbs=\app\api\model\BydUser::where('id',$data['userid'])->find();
//        if($agment['state']==0 || $agment['state']==8 || $agment['state']==9){
//            $bbsreal=BydUserSale::where('user_id',$data['userid'])->find();
//            if(!empty($des)){
//                $name=$bbsreal['name'].$bbsreal['idcart'];
//            }else{
//                $name='乙方';
//            }
//        }elseif ($agment['state']==1 || $agment['state']==10 || $agment['state']==11){
//            $des=BydDesigner::where('user_id',$data['userid'])->find();
//            if(!empty($des)){
//                $name=$des['username'].$des['idcart'];
//            }else{
//                $name='乙方';
//            }
//        }else{
//            $name='乙方';
//        }
        //if(!empty($agment) && $agment['state']==)

        $arrs=$agment['content'];
        //$arrs=str_replace('{$name}',$name,$arrs);
        $arrs=str_replace('{$star}',$startime,$arrs);
        $arrs=str_replace('{$end}',$endtime,$arrs);
        if(!empty($agment) && $agment['state']==12){
            $findsale=BydUserSale::where('user_id',$data['userid'])->find();
           $builddsd=BydDesignerArea::where('id',$data['lpid'])->find();//区
           $builddsds=BydDesignerArea::where('id',$builddsd['pid'])->find();//市
           $builddsdss=BydDesignerArea::where('id',$builddsds['pid'])->find();//省
            $nameqw=$findsale['name'];
            $idcar=$findsale['idcart'];
            $names="$nameqw$idcar";
            $onname="$nameqw";
            $arrs=str_replace('{$name}',$names,$arrs);
            $arrs=str_replace('{$onname}',$onname,$arrs);
            $arrs=str_replace('{$sheng}',$builddsdss['title'],$arrs);
            $arrs=str_replace('{$shi}',$builddsds['title'],$arrs);
            $arrs=str_replace('{$qu}',$builddsd['title'],$arrs);
        }
        $data['title']=$arrs;
    }


//    }
    $find=BydUserAg::where('user_id',$data['userid'])->where('agid',$data['agid'])->where('lpid',$data['lpid'])->find();
    if(empty($find)){
        $add=new BydUserAg();
        $add->data([
            'user_id'=>$data['userid'],
            'content'=>$data['title'],
            'status'=>0,
            'agid'=>$data['agid'],
            'lpid'=>$data['lpid'],
            'realname'=>$realname,
            'idcart'=>$sfz,
            'qy'=>0,
            'endtime'=>time()+86400*365
        ]);
        $add->save();
        if($add){
            $this->success('请求成功');
        }
    }else{
        $update=BydUserAg::where('user_id',$data['userid'])->where('agid',$data['agid'])->update(['qy'=>0,'status'=>0,'endtime'=>null]);
        $add=new BydUserAg();
        $add->data([
            'user_id'=>$data['userid'],
            'content'=>$data['title'],
            'agid'=>$data['agid'],
            'lpid'=>$data['lpid'],
            'realname'=>$realname,
            'idcart'=>$sfz,
            'qy'=>0,
            'endtime'=>time()+86400*365
        ]);
        $add->save();
        if($add){
            $this->success('请求成功1');
        }
        if(empty($data['userid']))$this->error('请登录');
    }
}
    /**
     * 取消续约
     * @param integer $userid ` '用户id',
     * @param integer $title ` '楼盘名称',
     * @param integer $lpid ` '楼盘id',
     *
     */
    public function qxment(){
        $data = $this->request->request('');
        $title = $this->request->request('title');
        $lpid = $this->request->request('lpid');
        if($title){
            $data['title']=$title;
        }else{
            $data['title']='';
        }
        if($lpid){
            $data['lpid']=$lpid;
        }else{
            $data['lpid']=0;
        }
        if(empty($data['user_id']))$this->error('请登录');
        $find=BydUserAg::where('user_id',$data['user_id'])->where('agid',$data['agid'])->find();
        if(empty($find)){
            $add=new BydUserAg();
            $add->data([
                'user_id'=>$data['user_id'],
                'content'=>$data['title'],
                'agid'=>$data['agid'],
                'lpid'=>$data['lpid'],
                'qy'=>0,
                'endtime'=>time()+86400*365
            ]);
            $add->save();
            if($add){
                $this->success('请求成功');
            }
        }else{
            $update=BydUserAg::where('user_id',$data['user_id'])->where('agid',$data['agid'])->update(['qy'=>0,'status'=>0,'endtime'=>null]);
            if($data['state']==0){
                $userbbs=\app\api\model\BydUser::where('id',$data['user_id'])->update(['bbs'=>0]);
                $usersale=BydUserSale::where('user_id',$data['user_id'])->delete();
            }else{
                $userbbs=\app\api\model\BydUser::where('id',$data['user_id'])->update(['des'=>0]);
                $usersale=BydDesigner::where('user_id',$data['user_id'])->delete();
            }
                $this->success('请求成功1');
                $agment=BydAgreement::find($data['agid']);
        }
    }
/**
 * 用户已签约协议
 * @param integer $userid ` '用户id',
 */
public function myag(){
    $data = $this->request->request('');
    if(empty($data['userid']))$this->error('请登录');
    if($data['id']==0){
        $find=BydUserAg::where('user_id',$data['userid'])->where('status',1)->field('id,agid')->order('id desc')->select();
    }else{
        $find=BydUserAg::where('id',$data['id'])->where('status',1)->field('id,agid,content')->order('id desc')->select();
    }
    if(!empty($find)){

        foreach ($find as &$v){
            if($data['id']==0){
                $v['ag']=BydAgreement::where('id',$v['agid'])->field('id,name')->find();
            }else{
                $v['ag']=BydAgreement::where('id',$v['agid'])->find();

            }
        }
        $this->success('请求成功',['status'=>$find]);
    }else{
        $this->error('暂无数据');
    }
}
/**
 * 智慧薪完善个人信息
 * @param integer $bankid ` '银行卡号',
 * @param integer $bankname ` '开户行',
 * @param integer $idcardnum ` '身份证号码',
 * @param integer $realname ` '真实姓名',
 * @param integer $userid ` '用户id',
 */
public function zhxmy(){
    $data = $this->request->request('');
    if(empty($data['bankid']) || empty($data['bankname']) || empty($data['idcardnum']) || empty($data['realname']))$this->error('请登录');
    $update=\app\admin\model\BydUser::where('id',$data['userid'])->update(['bankid'=>$data['bankid'],'bankname'=>$data['bankname'],'idcardnum'=>$data['idcardnum'],'realname'=>$data['realname']]);
    if($update){
        $this->success('请求成功');
    }else{
        $this->error('修改失败,请修改信息');
    }
}
/**
 * 提佣申请
 * @param integer $userid ` '用户id',
 * @param integer $orderid ` '订单id',
 */
public function sqty(){
    $data = $this->request->request('');
    if(empty($data['userid'])) $this->error('请登录');
    $find=\app\admin\model\BydUser::find($data['userid']);

    if(empty($find))$this->error('用户信息不正确');
    $bbs=BydIden::where('id',$find['bbs'])->find();
    if(empty($find['freelance_id']))$this->error('请注册完成智慧薪注册');
    $sale=BydUserSale::where('user_id',$data['userid'])->order('id desc')->find();
    if(!empty($data['orderid'])){
        $price=BydDispro::where('id','in',$data['orderid'])->sum('price');
        $pro=BydDispro::where('id','in',$data['orderid'])->select();

        $add=new BydUserTy();
        foreach ($pro as $v){
            if($v['type']==0){
                $v['types']='购买';
                $disfind=BydDistri::where('user_id',$v['user_id'])->find();
                $level=\app\admin\model\BydIdentity::where('id',$v['level'])->find();
               // print_r($level['myproduct']);die;
                if($disfind['pid']==$v['pid']){
                    $bl=$level['myproduct'];
                }else{
                    $bl=$level['sonproduct'];
                }
            }else{
                $v['types']='拉新';
                $bl=0;
            }
            $add=[
                'username'=>$find['username'],
                'realname'=>$find['realname'],
                'idcard'=>$find['idcardnum'],
                'userid'=>$data['userid'],
                'orderid'=>$v['order_id'],
               'type'=>$v['types'],
                'auto'=>0,
                'bl'=>$v['price'],
                'sfbh'=>$sale['bh'],
                'yhid'=>$find['bankid'],
                'price'=>$v['price'],
                'cjprice'=>$v['cjprice'],
                'addtime'=>$v['createtime'],
                'level'=>$find['bbs'],
            ];
            //$add->save();
            $cre=BydUserTy::create($add);
        }
    }
//    $add=new BydUserTy();
//    $add->data([
//        'username'=>$find['username'],
//        'realname'=>$find['realname'],
//        'userid'=>$data['userid'],
//        'orderid'=>$data['orderid'],
//        'auto'=>0,
//        'price'=>$price
//
//    ]);
//    $add->save();
    if($add){
        $arr=explode(",",$data['orderid']);
        foreach ($arr as $v){
//                        $where['id']=['eq',$v];
//                        $edit=\app\admin\model\BydDispro::where($where)->update(['tixian'=>1]);
            $user =new \app\admin\model\BydDispro();
            $user->save([
                'sq'  => '1',
            ],['id' => $v]);
        }
        //$ediesq=BydDispro::where('id','in',$data['orderid'])->update(['sq'=>1]);
        $this->success('申请成功');
    }else{
        $this->error('申请失败');
    }
}
/**
 *资讯中心
 * @param integer $limit ` '分页条数',
 */
public function pots(){
    $data = $this->request->request('');
    $arr=BydPots::where('switch',1)->order('weigh desc')->paginate($data['limit']);
    if(empty($arr))$this->error('暂无数据');
    $this->success('请求成功',['status'=>$arr]);
}
/**
 * 优惠劵渲染
 * @param integer $id ` '优惠劵id',
 */
public function cupons(){
    $data = $this->request->request('');
    if($data['id']>0){
        $arr=BydCupon::where('switch',1)->where('endtime','>',time())->where('id',$data['id'])->select();
    }else{
        $arr=BydCupon::where('switch',1)->where('endtime','>',time())->select();
    }

    foreach($arr as $key => $val)
    {
        $val['content'] = str_replace("/uploads/","https://bao.scwushen.com/uploads/",$val['content']);
        $arr[$key] = $val;
    }


    if(empty($arr))$this->error('暂无数据');
    $this->success('请求成功',['status'=>$arr]);
}
/**
 * 购买优惠劵
 * @param integer $coupons_id ` '优惠劵id',
 * @param integer $user_id ` '用户id',
 */
public function paycupons(){
    $osn = $this->getOrderNumber('CUP');
    $data = $this->request->request('');
    if(empty($data['user_id']) || empty($data['coupons_id']))$this->error('参数不全');
    $cre['coupons_id']=$data['coupons_id'];
    $cre['user_id']=$data['user_id'];
    $cre['payid']=$osn;
    $crecup=BydUsercupons::create($cre);
    if($crecup){
        $user=\app\admin\model\BydUser::find($data['user_id']);
        if(empty($user))$this->error('用户不存在');
        $findcup=BydCupon::where('id',$data['coupons_id'])->find();
        if(empty($findcup))$this->error('优惠劵不存在');
        $config = [
            'app_id'    => 'wx00e9e5b843259a9d',
            'mch_id'    => '1584376091',
            'key'       => 'TjRUCktaUcR6RQqCksBtwKRY8KwSTC4M',
            'secret'    => 'cce6015196dbba888133f9a3613b18b7',
            'notify'    => 'http://bao.scwushen.com/index.php/api/notify/cupons',
        ];
        $obj = new Wx( $config );
        $money = $findcup['price'];//$data['price']
        $data = [
            'body' => '宝云邸',
            'out_trade_no' => $osn, //客户订单号,
            'total_fee'=> $money * 100,
            'trade_type'    => 'JSAPI',
            'openid'    => $user['openid'],
        ];
        $ret = $obj->unifiedOrder( $data );
        return json($ret);
    }
}
/**
 * 我的优惠劵
 * @param integer $user_id ` '用户id',
 */
public function mycupons(){
    $data = $this->request->request('');
    $user=\app\admin\model\BydUser::find($data['user_id']);
    if(empty($user))$this->error('用户不存在');
    $mycup=BydUsercupons::where('user_id',$data['user_id'])->where('states',1)->select();
    if(empty($mycup))$this->error('暂无优惠劵');
    foreach ($mycup as &$v){
        $v['cupons']=BydCupon::find($v['coupons_id']);
    }
    $this->success('请求成功',['status'=>$mycup]);
}
    /**
     * [把返回的数据集转换成树形结构Tree]
     * @param array  $list 要转换的数据集
     * @param string $pid 父级ID键名
     * @param string $pk ID键名
     * @param string $child 子集键名
     * @param int    $root 一级菜单的parent_id 的值 （默认 0）
     * @return array
     */
    public static function listToTree($list, $pk = 'id', $pid = 'pid', $child = 'child', $root = 0)
    {
        // 创建Tree
        $tree = array();
        if (is_array($list)) {
            // 创建基于主键的数组引用
            $refer = array();
            foreach ($list as $key => $data) {
                $refer[$data[$pk]] =& $list[$key];
            }
            foreach ($list as $key => $data) {
                // 判断是否存在parent
                $parentId = $data[$pid];
                if ($root == $parentId) {
                    $tree[] =& $list[$key];
                } else {
                    if (isset($refer[$parentId])) {
                        $parent           =& $refer[$parentId];
                        $parent[$child][] =& $list[$key];
                    }
                }
            }
        }
        return $tree;
    }
/**
 * 业务地图渲染
 * @param integer $pid ` '区域id',
 */
public function map(){
    $data = $this->request->request('');
    $pid = $this->request->request('pid');
   if($pid==0){
       $arr=db('BydDesignerArea')->where('pid',0)->where('level',1)->where('num','>',0)->order('weigh desc')->select();
   }else{
       $arr=db('BydDesignerArea')->where('pid',$pid)->where('num','>',0)->order('weigh desc')->select();
   }

    //$tree=$this->listToTree($arr);
    $this->success('请求成功',['status'=>$arr]);
}
/**
 * C端用户给设计师傅打分
 * @param integer $des_id` '设计师id',
 * @param integer $user_id ` '用户id',
 * @param integer $one ` '评分1',
 * @param integer $two ` '评分2',
 * @param integer $three ` '评分3',
 * @param integer $four ` '评分4',
 * @param integer $all ` '总评分',
 */
public function pf(){

    $data = $this->request->request('');
    if(empty($data['user_id']) || empty($data['des_id']))$this->error('参数不全');
    $cre['des_id']=$data['des_id'];
    $cre['user_id']=$data['user_id'];
    $cre['one']=$data['one'];
    $cre['two']=$data['two'];
    $cre['three']=$data['three'];
    $cre['four']=$data['four'];
    $cre['all']=$data['all'];
    $crecup=DesPf::create($cre);
    if($crecup){
        $this->success('请求成功');
    }else{
        $this->error('服务器繁忙请稍后再试');
    }
}
/**
 * 设计师立即评分
 * @param integer $yyid ` '预约单号',
 */
public function desljpf(){
    $data = $this->request->request('');
    $order=\app\admin\model\BydDesignerMake::where('orderid',$data['yyid'])->find();
    if(empty($order))$this->error('订单不存在');
    $des=BydDesigner::find($order['des_id']);
    if(empty($des))$this->error('设计师不存在');
    $this->success('请求成功',['status'=>$des]);
}
/**
 * 业务地图楼盘
 * @param integer $id ` '区域id',
 */
public function lpmap(){
    $data = $this->request->request('');
    $find=SoleBuilding::where('area_id',$data['id'])->order('weigh desc')->field('id,area_id,title,standard,address,trun_time,house_type,house_area,house_imgs,aid,sign_did,sign_bid')->select();
    if(empty($find))$this->error('暂无楼盘');



//    foreach ($find as &$v){
//        $v['ag']=BydAgreement::find($v['aid']);
//    }
    $this->success('请求成功',['status'=>$find]);
}
    /**
     * 楼盘协议
     * @param integer $id ` '楼盘id',
     */
    public function lpagreement(){
        $data = $this->request->request('');
        $find=SoleBuilding::where('id',$data['id'])->order('weigh desc')->field('id,area_id,title,standard,address,trun_time,house_type,house_area,house_imgs')->find();
        if(empty($find))$this->error('暂无楼盘');
        $qu=BydDesignerArea::where('id',$find['area_id'])->find();
        $shi=BydDesignerArea::where('id',$qu['pid'])->find();
        $sheng=BydDesignerArea::where('id',$shi['pid'])->find();
        $dagreement=BydAgreement::where('state',6)->find();
        $bagreement=BydAgreement::where('state',7)->find();
        $name=$find['title'];
        $bz=$find['standard'];
        $adedress=$find['address'];
        $time=$find['trun_time'];
        $huxin=$find['house_type'].$find['house_area'];
        $array=explode(",", $find['house_imgs']);
        foreach ($array as $v){
            $image[]='https://bao.scwushen.com/'.$v;
        }
//                print_r($images);die;
//                $image=explode(',',$images);
//                print_r($params['house_imgs']);die;
        //$path= APP_PATH.'api/view/demo/abc.html';
        //$opempath=fopen($path,'a+');
        $arr=$dagreement['content'];

        $arr=str_replace('{$name}','姓名身份证',$arr);
        $arr=str_replace('{$oname}','姓名',$arr);
        $arr=str_replace('{$star}','当前时间',$arr);
        $arr=str_replace('{$end}','明年截止时间',$arr);
        $arr=str_replace('{$standard}',$find['standard'],$arr);
        $arr=str_replace('{$trun_time}',$find['trun_time'],$arr);
        //$arrs=str_replace('{$name}','乙方姓名',$arrs);
        $arr=str_replace('{$sheng}',$sheng['title'],$arr);
        $arr=str_replace('{$shi}', $shi['title'],$arr);
        $arr=str_replace('{$qu}',$qu['title'],$arr);
        $arr=str_replace('{$lp}',$find['title'],$arr);
        $imagestring='';
        foreach ($image as $v){
            $imagestring.='<img src='.$v.' style="max-width:100%;height:auto;display:block;margin:0px auto;">';
            //$imagestring.='<image  src='.$v.' mode="widthFix"></image>';
        }
        $arr=str_replace('{$image}',$imagestring,$arr);
        $find['dcontents']=$arr;

        $arrs=$bagreement['content'];

        //$arrs=str_replace('{$name}',$name,$arrs);
        $arrs=str_replace('{$name}','姓名身份证',$arrs);
        $arrs=str_replace('{$oname}','姓名',$arrs);
        $arrs=str_replace('{$standard}',$find['standard'],$arrs);
        $arrs=str_replace('{$trun_time}',$find['trun_time'],$arrs);
        //$arrs=str_replace('{$name}','乙方姓名',$arrs);
        $arrs=str_replace('{$star}','当前时间',$arrs);
        $arrs=str_replace('{$end}','明年截止时间',$arrs);
        $arrs=str_replace('{$sheng}',$sheng['title'],$arrs);
        $arrs=str_replace('{$shi}', $shi['title'],$arrs);
        $arrs=str_replace('{$qu}',$qu['title'],$arrs);
        $arrs=str_replace('{$lp}',$find['title'],$arrs);
        $imagestring='';
        foreach ($image as $v){
            $imagestring.='<img src='.$v.'>';
        }
        $arrs=str_replace('{$image}',$imagestring,$arrs);
        $find['bcontents']=$arrs;
        //print_r($find['bcontents']);die;
//    foreach ($find as &$v){
//        $v['ag']=BydAgreement::find($v['aid']);
//    }
        $this->success('请求成功',['status'=>$find]);
    }
    /**
     * 区域查看状态
     */
//    public function mapstations(){
//        $data = $this->request->request('');
//        $user=\app\admin\model\BydUser::find($data['user_id']);
//        if(empty($user))$this->error('请登录');
//
//    }
/**
 * 业务地图查看状态
 * @param integer $user_id` '用户id',
 * @param integer $bid` '楼盘id',
 * @param integer $type` '状态',
 */
public function mapstation(){
    $data = $this->request->request('');
    $user=\app\admin\model\BydUser::find($data['user_id']);

    if(empty($user))$this->error('请登录');

    if(!isset($data['bid']) || !isset($data['type']) || !in_array($data['type'], array(2,1,0)))
    {
        $this->error('参数错误');
    }
    if($user['bbs']==1){
        if($user['des']==4 && $data['type']==1){
            //为d3
            $find1=SoleAgency::
            where('bid',$data['bid'])->
            where('user_id',$data['user_id'])->
            where('sole_type',$data['type'])->order('id desc')->find();//是否有人申请
            if(!empty($find1))
            {
                if($find1['state']==0){
                    $this->success('您的独家设计权正在审核','您的独家设计权已提交,正在审核中',0);
                }elseif($find1['state']==1){
                    $this->success('您的独家设计权已通过','您的申请已通过，请及时上传对应楼盘方案及户型攻略。',3);
                }else{
                    $this->success('您的独家设计权已被驳回',$find1['reason'],4);
                }
            }else{
//                $find1=SoleAgency::
//                where('bid',$data['bid'])->
//                where('user_id',$data['user_id'])->
//                where('sole_type',1)->where('state',2)->order('id desc')->find();//是否有人申请
//                if(!empty($find1)){
                    $this->success('请签约楼盘独家设计权','',1);
//                }
//                if($data['type']==0){
//                    $this->success('请签约推广权','',5);
//                }else{
//                }
            }
        }else{
            $solebuilding=SoleBuilding::where('id',$data['bid'])->find();
            $find=Apply::where('user_id',$data['user_id'])->where('lp',$data['bid'])
                ->where('state',0)->order('id desc')->find();
            $findar=SoleAgency:: where('bid',$data['bid'])->
            where('user_id',$data['user_id'])->
            where('sole_type',1)->where('state',1)->order('id desc')->find();//查询D端身份是否通过
            if($data['type']==0  && empty($find) && !empty($findar)){
                $this->success('请签约推广权','',5);
            }else{
                $this->success('申请成功','',5);
            }
//            if(empty($find)){
//                $this->success('请签约推广权','',0);
//            }else{
//                $this->success('请勿重复签约推广权','',0);
//            }
        }
    }elseif($user['bbs']==2){
//        if($user['des']==4){
            //为d3
            $find1=SoleAgency::
            where('bid',$data['bid'])->
            where('user_id',$data['user_id'])->
            where('sole_type',$data['type'])->order('id desc')->find();//是否有人申请
            if(!empty($find1))
            {
                if($data['type']==0){
                    if($find1['state']==0){
                        $this->success('美居独家经营权申请正在审核','楼盘申请成功，请留意系统消息查看审核结果',7);
                    }elseif($find1['state']==1){
                        $this->success('美居独家经营权申请已通过','您的申请已通过！',8);
                    }else{
                        $this->success('美居独家经营权申请被拒绝',$find1['reason'],9);
                    }
                }elseif($data['type']==1){
                    if($find1['state']==0){
                        $this->success('美居独家设计权申请正在审核','楼盘申请成功，请留意系统消息查看审核结果',0);//msg为设计师弹窗的title data为内容
                    }elseif($find1['state']==1){
                        $this->success('美居独家设计权申请已通过','您的申请已通过，请及时上传对应楼盘方案及户型攻略。',3);
                    }else{
                        $this->success('美居独家设计权申请被拒绝',$find1['reason'],4);
                    }
                }
            }else{
                $this->success('暂无申请数据','',10);
            }
//        }else{
//            $find=Apply::where('user_id',$data['user_id'])->where('lp',$data['bid'])
//                ->where('state',0)->find();
//            if(empty($find)){
//                $this->success('请签约推广权','',0);
//            }else{
//                $this->success('请勿重复签约推广权','',0);
//            }
//
//        }
    }elseif ($user['bbs']==3){
        if($user['des']==4 && $data['type']==1){
            $find1=SoleAgency::
            where('bid',$data['bid'])->
            where('user_id',$data['user_id'])->
            where('sole_type',$data['type'])->order('id desc')->find();//是否有人申请
            if(!empty($find1))
            {
                if($find1['state']==0){
                    $this->success('您的独家设计权正在审核','您的独家设计权已提交,正在审核中',0);
                }elseif($find1['state']==1){
                    $this->success('您的独家设计权已通过','您的申请已通过，请及时上传对应楼盘方案及户型攻略。',3);
                }else{
                    $this->success('您的独家设计权已被驳回',$find1['reason'],4);
                }
            }else{
//                $find1=SoleAgency::
//                where('bid',$data['bid'])->
//                where('user_id',$data['user_id'])->
//                where('sole_type',1)->where('state',2)->order('id desc')->find();//是否有人申请
//                if(!empty($find1)){
                $this->success('请签约楼盘独家设计权','',1);
//                }
//                if($data['type']==0){
//                    $this->success('请签约推广权','',5);
//                }else{
//                }
            }
        }
        $find1=SoleAgency::
        where('bid',$data['bid'])->
        where('user_id',$data['user_id'])->
        where('sole_type',$data['type'])->order('id desc')->find();//是否有人申请
        if(!empty($find1))
        {
                if($find1['state']==0){
                    $this->success('您的独家区域经营权已提交,正在审核中','',11);//
                }elseif($find1['state']==1){
                    $this->success('您的独家区域经营权已通过','',12);//区域弹窗通过提示
                }else{
                    $this->success('美居独家区域经营权',$find1['reason'],13);//弹窗的title
                }
        }else{
            $find12=SoleAgency::
//            where('bid',$data['bid'])->
            where('user_id',$data['user_id'])->
            where('sole_type',$data['type'])->order('id desc')->find();//是否有人申请
            if(empty($find12)){
                $this->success('暂无申请数据','',14);
            }else{
                if($find12['state']==1){
                    $this->success('您已签约其他区域','',20);//后台通过后点其他区域提示
                }else{
                    $this->success('您有其他区域申请正在审核，请耐心等待','',20);//点其他区域提示
                }
            }
        }

    }
    # 是否有申请记录， 0未
    # 是否被签约， 1  user_id 一致 申请已通过， 不一致， 楼盘已被签约
    # 是否有自己的驳回， 1有申请
//   if($user['bbs']>1 || $user['des']==3 || $user['des']==4){
//       # 查询是否被申请
//       $find1=SoleAgency::where('state', 1)->
//       where('bid',$data['bid'])->
//       where('sole_type',$data['type'])->find();//是否有人申请
//       if(!empty($find1))
//       {
//           if($find1['user_id'] == $data['user_id']) $this->success('您已签约楼盘','',1);
//           else $this->error('楼盘已被签约','',0);
//       }
//
//       # 查询是否有申请中的记录
//       $find0=SoleAgency::where('state', 0)->
//       where('bid',$data['bid'])->
//       where('sole_type',$data['type'])->order('id desc')->find();//是否有人申请
//       if(!empty($find0))
//       {
//           if($find0['user_id'] == $data['user_id']) $this->success('您的申请正在审核中',[],2);
//           else $this->success('楼盘已被申请,正在审核中','',3);
//       }
//
//       $find2=SoleAgency::where('user_id',$data['user_id'])->where('state', 2)->
//       where('bid',$data['bid'])->
//       where('sole_type',$data['type'])->order('id desc')->find();//是否有人申请
//       if(!empty($find2))
//       {
//           $this->success('您的申请被驳回', ['reason' => $find2['reason'], 'code'=>3],0);
//       }
//
//       $this->success('暂无申请数据','',0);
//   }


//    $find=SoleAgency::where('user_id',$data['user_id'])->
//        where('bid',$data['bid'])->
//        where('sole_type',$data['type'])->find();//是否本人申请
//
//    //$findsd=SoleAgency::where('user_id',$data['user_id'])->where('bid',$data['bid'])->where('sole_type',$data['type'])->find();//B端申请
//    //$bulid=SoleBuilding::find($data['bid']);
//    if(empty($find))$this->error('暂无申请数据');
//    if(!empty($find)){
//        if($find['state']==0){
//            $this->error('您的申请正在审核中',null,2);
//        }elseif($find['state']==1){
//            $this->success('您的申请已通过');
//        }else{
//            $this->error('您的申请被驳回',$find['reason'],3);
//        }
//    }
//    if(!empty())
//    if(empty($findsd) && empty($bulid['sign_did'])){
//        $this->error('可申请D端身份');
//    }elseif(empty($findsd) && !empty($bulid['sign_did'])){
//        $this->error('该楼盘已有设计师');
//    }elseif(!empty($findsd)){
//        if($findsd['state']==0){
//            $this->error('您的申请正在审核中',null,2);
//        }elseif($findsd['state']==1){
//            $this->success('您的申请已通过');
//        }else{
//            $this->error('您的申请被驳回',$findsd['reason'],3);
//        }
//    }
//    if(empty($find) && empty($bulid['sign_bid']))
//    {
//        $this->error('可申请B端身份');
//    }elseif(empty($find) && !empty($bulid['sign_did'])){
//        $this->error('该楼盘已有设计师');
//    }else{
//        if($findsd['state']==0){
//            $this->error('您的申请正在审核中',null,2);
//        }elseif($findsd['state']==1){
//            $this->success('您的申请已通过');
//        }else{
//            $this->error('您的申请被驳回',$find['reason'],3);
//        }
//    }
    //$this->error('可申请B端身份');
//    if(empty($findsd))$this->error('D端暂无申请数据');

//    if($find['state']==0){
//        $this->error('您的申请正在审核中',null,2);
//    }elseif($find['state']==1){
//        $this->success('您的申请已通过');
//    }else{
//        $this->error('您的申请被驳回',$find['reason'],3);
//    }
//    $findsd=SoleAgency::where('user_id',$data['user_id'])->where('bid',$data['bid'])->where('sole_type',0)->find();//B端申请

}
/**
 * 业务地图搜索
 * @param integer $id` '区域id',
 * @param integer $title` '搜索内容',
 */
public function likelp(){
    $data = $this->request->request('');
    $where['area_id']=['eq',$data['id']];
    $where['title']=['like','%'.$data['title'].'%'];
    $arr=SoleBuilding::where($where)->select();
    if (empty($arr))    $this->error('暂无数据');
    foreach ($arr as &$v){
        $v['ag']=BydAgreement::find($v['aid']);
    }
    $this->success('请求成功',['status'=>$arr]);
}
/**
 * 培训费用申请渲染
 * @param integer $user_id` '用户id',
 * @param integer $start` '开始时间',
 * @param integer $end` '结束时间',
 */
public function pxxr(){
    $data = $this->request->request('');
    if(empty($data['user_id'])) $this->error('请登录');
    $where['createtime']=['between time',[$data['start'],$data['end']]];
    $where['money']=['eq',1];
    $where['type']=['eq',1];
    $where['pid']=['eq',$data['user_id']];
    $arr=BydDispro::where($where)->select();
    if(!empty($arr)){
        foreach ($arr as &$v){
            $v['user']=\app\api\model\BydUser::find($v['user_id']);
        }
    }
    if(empty($arr))$this->error('暂无数据');
    $this->success('请求成功',['status'=>$arr]);
}
/**
 * 培训费申请
 * * @param integer $user_id` '用户id',
 * * @param integer $id` '消费明细的id',
 */

public function pxsq(){
    $data = $this->request->request('');
    if(empty($data['user_id'])) $this->error('请登录');

    $arr=BydDispro::where('id','in',$data['id'])->select();
    if(empty($arr))$this->error('条件不符');
    $add=new Train();
    foreach ($arr as $v){
        $add->data([
            'user_id'=>$data['user_id'],
            'price'=>$v['price'],
            'did'=>$v['id'],
            'image'=>$data['image']
        ]);
        $add->save();
    }

    if($add){
        \think\Cache::set('px',1,3600);
        $this->success('申请成功,请等待平台审核');
    }else{
        $this->error('服务器繁忙,请稍后再试');
    }
}
/**
 * 推送vr信息
 */
public function vrnews(){
    $data = $this->request->request('');
    if(empty($data['user_id'])) $this->error('请登录');
    $user=\app\api\model\BydUser::find($data['user_id']);
    if(empty($user)) $this->error('用户不存在');
    $arr=[
        'openid'=>$user['openid'],
        'thing2'=>"请复制上方链接到浏览器打开",//$data['news'],
        'thing6'=>$data['news'],
    ];
    $new=new News();
    $news=$new->vr($arr);
   
    if($news){
        $this->success('请求成功');
    }else{
        $this->error('服务器繁忙,请稍后再试');
    }
}
/**
 * 错误信息记录
 */
public function cuxx(){
    $data = $this->request->request('');
  $add=new \app\admin\model\Cwxx();
  $add->data([
      'content'=>$data['content']
  ]);
  $add->save();
  if($add){
      $this->success('请求成功');
  }else{
      $this->error('服务器繁忙,请稍后再试');
  }
    //$cre=\app\admin\model\Cwxx::create($data['content']);
}
    public function qwe(){
        $sslCert = substr($_SERVER['DOCUMENT_ROOT'],0,-6) .'/byd-wx-rsakey/bydwxssl_cert.pem';
        $sslKey = substr($_SERVER['DOCUMENT_ROOT'],0,-6) .'/byd-wx-rsakey/bydwxssl_key.pem';
  print_r(substr($_SERVER['DOCUMENT_ROOT'],0,-6));die;
        $order=[
        'orderid'=>'BYD_20220425171049605743'
    ];
        $orderson=BydOrderSon::where('porderid',$order['orderid'])->select();
        if(!empty($orderson)) {
            foreach ($orderson as $v) {

                $bl = Bpay::where('id', $v['tcbl'])->find();
                $fwbl = Sermoney::where('id', $v['fwbl'])->find();
                if (!empty($bl)) {
                    $one = $v['price'] * $bl['one'] / 100;
                    $two = $v['price'] * $bl['two'] / 100;
                    $three = $v['price'] * $bl['three'] / 100;
                    $edit = BydOrderSon::where('id', $v['id'])->update(['one' => $one, 'two' => $two, 'three' => $three]);
                }
                if (!empty($fwbl)) {
                    $ones = $v['price'] * $fwbl['one'] / 100;
                    $twos = $v['price'] * $fwbl['two'] / 100;
                    $threes = $v['price'] * $fwbl['three'] / 100;
                    $fours = $v['price'] * $fwbl['four'] / 100;
                    $bz = $ones + $twos + $threes + $fours;

                    $edits = BydOrderSon::where('id', $v['id'])->update(['bz' => $bz]);
                }
            }
        }
            die;
       $data=[
           'user_id'=>114,
           'idcar'=>2
       ];
        //微信支付成功后

        $osn = date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);//订单号
        $user=new \app\api\model\BydUser();

        $sale=BydUserSale::where('user_id',$data['user_id'])->find();
        if(!empty($sale)){
            $saleedit=BydUserSale::where('user_id',$data['user_id'])->update(['level'=>$data['idcar']]);
        }
        $find=\app\admin\model\BydIden::where('id',$data['idcar'])->find();//查询身份分佣金额
//            $rand=rand(1,9999);
//            $head=$find['idenhead'];
//            $num="$head$rand";
        $num="b-" .  str_pad(rand(1,9999), 5, '0',  STR_PAD_LEFT);
        $dis=BydDistri::where('user_id',$data['user_id'])->find();//查询上级
        $users=$user->where('id',$data['user_id'])->find();
         $bbs=$users['bbs'];

        if($dis ){
if($bbs<1){


            $save=$user->where('id',$data['user_id'])->update(['bbs'=>$data['idcar']]);//修改对应的身份
            if($dis['family']>0){
//                $father=\app\admin\model\BydUser::where('id',$data['pid'])->find();//查看父级身份
//                if($father['bbs']>0){
//                    $level=\app\admin\model\BydIdentity::find($father['bbs']);
//                    $ftc=$order['price']*$level['myproduct']/100;//上级所得提成
//                }
////                    $ftc=$order['price']*$level['myproduct']/100;//上级所得提成
//                $gfather=\app\admin\model\BydUser::where('id',$pro['family'])->find();//查看第一级别身份
//                $levels=\app\admin\model\BydIdentity::find($gfather['bbs']);
                $pid=\app\admin\model\BydUser::find($dis['pid']);
                $familyuser=BydUserSale::where('user_id',$dis['family'])->find();//查看上级身份
                if($familyuser['level']==3 || $familyuser['level']==2){
//                        $userfind=\app\admin\model\BydUser::find($data['user_id']);
//                        if($userfind['bbs']==0){
                    if($data['idcar']==1 || $data['idcar']==2 || $data['idcar']==3){
                        //有b1上级且购买bs
                        if($dis['family']==$dis['pid']){
                            //第一级与第二级为同一人
                            $price=BydIden::find(3);
                            $oneprice=BydIden::find($familyuser['level']);
                            if($data['idcar']==1){
                                $one=$oneprice['mynewmoney'];
                            }elseif ($data['idcar']==2){
                                $one=$oneprice['mynewmoneyt'];
                            }else{
                                $one=$oneprice['mynewmoneyr'];
                            }
                            $add = new BydDispro();
                            $add->data([
                                'cjprice'=>$find['money'],
                                'level'=>$data['idcar'],
                                'pid'  => $dis['pid'],
                                'state' =>  1,
                                'user_id' =>  $data['user_id'],
                                'type' => 1,
                                'order_id'=>$osn,
                                'money'=>0,
                                'price'=>$one
                            ]);
                            $add->save();
                            if($add){
                                $adds = new BydUserSale();
                                $editsale=$adds->where('user_id',$data['user_id'])->update(['level'=>$data['idcar'],'bh'=>$num]);
//                                    $adds->data([
//                                        'state' =>  0,
//                                        'user_id' =>  $data['user_id'],
//                                        'level'=>$data['idcar'],
//                                        'bh'=>$num
//                                    ]);
//                                    $adds->save();
                                //$sumcom=$user->where('id',$dis['pid'])->update(['bbs'=>$data['idcar']]);//修改身份标识
                            }
                            //$sumcoms=$user->where('id',$dis['pid'])->setInc('cancommission',$price['mynewmoney']);//可提现用金+40
                        }else{
                            //$familyuser=\app\admin\model\BydUser::find($dis['family']);//查看pid的身份
                            $piduser=\app\admin\model\BydUser::find($dis['pid']);//查看pid的身份
                            //第family上级分佣
                            $oneprice=BydIden::find($familyuser['level']);
                            $twoprice=BydIden::find(1);
                            if($data['idcar']==1){
                                $one=$oneprice['mysonmoney'];
                                $two=$twoprice['mynewmoney'];
                            }elseif ($data['idcar']==2){
                                $one=$oneprice['mysonmoneyt'];
                                $two=$twoprice['mynewmoneyt'];
                            }else{
                                $one=$oneprice['mysonmoneyr'];
                                $two=$twoprice['mynewmoneyr'];
                            }
                            if($piduser['bbs']==1){//如果为b1
                                //第pid上级分佣

                                $user = new BydDispro();
                                $list = [
                                    ['pid'=>$dis['family'],'state'=>1,'user_id'=>$data['user_id'],'type'=>1,'order_id'=>$osn,'price'=>$one,'money'=>1],
                                    ['pid'=>$dis['pid'],'state'=>1,'user_id'=>$data['user_id'],'type'=>1,'order_id'=>$osn,'price'=>$two,'money'=>0]
                                ];
                                $user->saveAll($list);
                                $adds = new BydUserSale();
                                $editsale=$adds->where('user_id',$data['user_id'])->update(['level'=>$data['idcar'],'bh'=>$num]);

//                                    $adds->data([
//                                        'state' =>  0,
//                                        'user_id' =>  $data['user_id'],
//                                        'level'=>$data['idcar'],
//                                        'bh'=>$num
//                                    ]);
//                                    $adds->save();
                                //$sumcom=\app\admin\model\BydUser::where('id',$data['user_id'])->update(['bbs'=>$data['idcar']]);//修改身份标识
                                $sumcoms=\app\admin\model\BydDistri::where('user_id',$data['user_id'])->update(['pid'=>$dis['pid']]);//修改退队关系列表
                            }elseif($piduser['bbs']==2){
                                $twoprice=BydIden::find(2);
                                if($data['idcar']==1){
                                    $two=$twoprice['mynewmoney'];
                                }elseif ($data['idcar']==2){
                                    $two=$twoprice['mynewmoneyt'];
                                }else{
                                    $two=$twoprice['mynewmoneyr'];
                                }

                                $oneprices=BydIdentity::find(2);
                                //第pid上级分佣
                                $user = new BydDispro();
                                $list = [
                                    ['pid'=>$dis['family'],'state'=>1,'user_id'=>$data['user_id'],'type'=>1,'order_id'=>$osn,'price'=>$one,'money'=>1],
                                    ['pid'=>$dis['pid'],'state'=>1,'user_id'=>$data['user_id'],'type'=>1,'order_id'=>$osn,'price'=>$two,'money'=>0]
                                ];
                                $user->saveAll($list);
                                $adds = new BydUserSale();
                                $editsale=$adds->where('user_id',$data['user_id'])->update(['level'=>$data['idcar'],'bh'=>$num]);

//                                    $adds->data([
//                                        'state' =>  0,
//                                        'user_id' =>  $data['user_id'],
//                                        'level'=>$data['idcar'],
//                                        'bh'=>$num
//                                    ]);
//                                    $adds->save();
                                //$sumcom=\app\admin\model\BydUser::where('id',$data['user_id'])->update(['bbs'=>$data['idcar']]);//修改身份标识
                                $sumcoms=\app\admin\model\BydDistri::where('user_id',$data['user_id'])->update(['pid'=>$dis['pid']]);//修改退队关系列表
                            }elseif($piduser['bbs']==3){

                                $twoprice=BydIden::find(3);
                                if($data['idcar']==1){
                                    $two=$twoprice['mynewmoney'];
                                }elseif ($data['idcar']==2){
                                    $two=$twoprice['mynewmoneyt'];
                                }else{
                                    $two=$twoprice['mynewmoneyr'];
                                }
                                //第pid上级分佣
                                $user = new BydDispro();
                                $list = [
                                    ['pid'=>$dis['family'],'state'=>1,'user_id'=>$data['user_id'],'type'=>1,'order_id'=>$osn,'price'=>$one,'money'=>1],
                                    ['pid'=>$dis['pid'],'state'=>1,'user_id'=>$data['user_id'],'type'=>1,'order_id'=>$osn,'price'=>$two,'money'=>0]
                                ];
                                $user->saveAll($list);
                                $adds = new BydUserSale();
                                $editsale=$adds->where('user_id',$data['user_id'])->update(['level'=>$data['idcar'],'bh'=>$num]);

//                                    $adds->data([
//                                        'state' =>  0,
//                                        'user_id' =>  $data['user_id'],
//                                        'level'=>$data['idcar'],
//                                        'bh'=>$num
//                                    ]);
//                                    $adds->save();
                                //$sumcom=\app\admin\model\BydUser::where('id',$data['user_id'])->update(['bbs'=>$data['idcar']]);//修改身份标识
                                $sumcoms=\app\admin\model\BydDistri::where('user_id',$data['user_id'])->update(['pid'=>$dis['pid']]);//修改退队关系列表
                            }


//                            $upsumcom=$user->where('id',$dis['pid'])->setInc('commission',$twoprice['mynewmoney']);//上级获得总用金+30
//                            $upsumcoms=$user->where('id',$dis['pid'])->setInc('cancommission',$twoprice['mynewmoney']);//上级获得可提现用金+30
//                            $uppsumcom=$user->where('id',$dis['family'])->setInc('commission',$oneprice['mysonmoney']);//上级获得总用金+10
//                            $uppsumcoms=$user->where('id',$dis['family'])->setInc('cancommission',$oneprice['mysonmoney']);//上级获得可提现用金+10
                        }
                    }else{

                        //有b1上级且购买b1
                        $price=BydIdentity::find(2);

                        $add = new BydDispro();
                        $add->data([
                            'cjprice'=>$find['money'],
                            'level'=>$data['idcar'],
                            'pid'  => $dis['family'],
                            'state' =>  1,
                            'user_id' =>  $data['user_id'],
                            'type' => 1,
                            'order_id'=>$osn,
                            'money'=>1,
                            'price'=>$price['mysonup']
                        ]);
                        $add->save();

                        if($add){

                            $adds = new BydUserSale();
                            $editsale=$adds->where('user_id',$data['user_id'])->update(['level'=>$data['idcar'],'bh'=>$num]);

//                                $adds->data([
//                                    'state' =>  0,
//                                    'user_id' =>  $data['user_id'],
//                                    'level'=>$data['idcar'],
//                                    'bh'=>$num
//                                ]);
//                                $adds->save();
                            $sumcom=$user->where('id',$data['user_id'])->update(['bbs'=>$data['idcar']]);//修改身份标识
                            $diss=new BydDistri();

                            $where['family']=array('eq',$dis['family']);
                            $where['id']=array('gt',$dis['id']);
                            //$where['pid']=array('eq',$data['user_id']);
//                        $where[]=['family','=',$dis['family']];
                            //$wheres['pid']=['eq',$data['user_id']];
                            $pid=$diss->isUpdate(true,$where)->save(['family'=>$data['user_id']]);//改下面得下级
                            $myself=$diss->where('user_id',$data['user_id'])->update(['family'=>0,'pid'=>0]);

                            // $pid=$diss->where($where)->find();


                        }
//                        $uppsumcom=$user->where('id',$dis['family'])->setInc('commission',$price['mysonup']);//上级获得总用金+700
//                        $uppsumcoms=$user->where('id',$dis['family'])->setInc('cancommission',$price['mysonup']);//上级获得可提现用金+700
//                        //购买后第二级为购买者的独立成一个团队

                    }
//                        }

                }elseif($familyuser['level']==1){
                    $piduser=\app\admin\model\BydUser::find($dis['pid']);//查看pid的身份
                    $oneprice=BydIden::find($piduser['bbs']);
//                        $userbbs=\app\admin\model\BydUser::find($data['user_id']);
//                        if($userbbs['bbs']==0){
                    if($data['idcar']==1){
                        $one=$oneprice['mynewmoney'];
                    }elseif ($data['idcar']==2){
                        $one=$oneprice['mynewmoneyt'];
                    }else{
                        $one=$oneprice['mynewmoneyr'];
                    }
                    $price=BydIden::find(1);
                    $add = new BydDispro();
                    $add->data([
                        'cjprice'=>$find['money'],
                        'level'=>$data['idcar'],
                        'pid'  => $dis['pid'],
                        'state' =>  1,
                        'user_id' =>  $data['user_id'],
                        'type' => 1,
                        'order_id'=>$osn,
                        'money'=>0,
                        'price'=>$one
                    ]);
                    $add->save();
                }

//                    }
            }else{
                $userfind=\app\admin\model\BydUser::find($data['user_id']);
                if($userfind['bbs']==0){
                    //c端升bs
                    $adds = new BydUserSale();
                    $adds->data([
                        'state' =>  0,
                        'user_id' =>  $data['user_id'],
                        'level'=>$data['idcar'],
                        'bh'=>$num
                    ]);
                    $adds->save();
                    $sale=new BydUserSale();
                    $disfind=BydDistri::where('user_id',$data['user_id'])->update(['level'=>$data['idcar']]);
                }else{
                    $save=$user->where('id',$data['user_id'])->update(['bbs'=>$data['idcar']]);//修改对应的身份

                    //散户bs升b1
                    $sale=new BydUserSale();

                    $pid=$sale->isUpdate(true,['user_id'=>$data['user_id']])->save(['level'=>$data['idcar'],'state'=>0,'bh'=>$num]);
                    $disfind=BydDistri::where('user_id',$data['user_id'])->update(['level'=>$data['idcar']]);
//                    $diss=new BydDistri();
//                    //$where['pid']=array('eq',$data['user_id']);
//                    $sonfind=$diss->where('pid',$data['user_id'])->select();
//                    if(!empty($sonfind)){
//                        foreach ($sonfind as $v){
//                            $where['family']=array('eq',$v['user_id']);
//                            $familyedit=$diss->isUpdate(true,$where)->save(['family'=>$data['user_id']]);//改下面得下级
//                        }
//                    }
//                    $where['family']=array('eq',$dis['family']);
//                    $where['id']=array('gt',$dis['id']);
////                        $where[]=['family','=',$dis['family']];
//                    //$where['user_id']=['eq',$data['user_id']];
//                    $pid=$diss->isUpdate(true,$where)->save(['family'=>$data['user_id']]);//改下面得下级
                }
            }
}else{
    $save=$user->where('id',$data['user_id'])->update(['bbs'=>$data['idcar']]);//修改对应的身份
    $sale=new BydUserSale();

    $pid=$sale->isUpdate(true,['user_id'=>$data['user_id']])->save(['level'=>$data['idcar'],'bh'=>$num]);
    $disfind=BydDistri::where('user_id',$data['user_id'])->update(['level'=>$data['idcar']]);
}

        }else{
            $save=$user->where('id',$data['user_id'])->update(['bbs'=>$data['idcar']]);//修改对应的身份

            //散户自主购买
            if($data['idcar']==1){
                $data['level']=1;
                $data['state']=1;
            }else{
                $data['level']=$data['idcar'];
                $data['state']=0;
            }
            //添加到身份列表
            $add = new BydDistri();
            $add->data([
                'pid'  => 0,
                'family' =>  0,
                'user_id' =>  $data['user_id'],
                'level'=>$data['idcar'],
            ]);
            $add->save();
            //添加销售员列表

            $adds = new BydUserSale();
            $editsale=$adds->where('user_id',$data['user_id'])->update(['level'=>$data['idcar'],'bh'=>$num]);
//                $adds->data([
//                    'state' =>  $data['state'],
//                    'user_id' =>  $data['user_id'],
//                    'level'=>$data['idcar'],
//                    'bh'=>$num
//                ]);
//                $adds->save();
        }



    }
    public function fou(){
        $data = $this->request->request('');
        if(empty($data['orderid']))$this->error('订单号不正确');
        $edit=BydShopOrder::where('orderid',$data['orderid'])->update(['cl'=>1]);
        $find=BydShopOrder::where('orderid',$data['orderid'])->find();

        if($find['twofw']==1){
            $user=$find['two'];
        }elseif($find['threefw']==1){
            $user=$find['three'];
        }else{
            $user=0;
        }
        $price=BydOrderSon::where('porderid',$data['orderid'])->sum('bz');
        if($price>0){
            $finduser=BydDispro::where('pid',$user)->find();
            if(!empty($finduser)){
                $upup=BydDispro::where('id',$finduser['id'])->setInc('price',$price);
                $edit=BydDispro::where('id',$finduser['id'])->update(['bz'=>1]);
                if($upup){
                    $this->success('请求成功');
                }else{
                    $this->error('请求失败');
                }
            }else{
                $this->error('服务器繁忙');
            }
//            $addthree = new BydDispro();
//            $addthree->data([
//                'cjprice' => $find['price'],
//                'level' => 0,
//                'pid' => $user,
//                'money' => 0,
//                'state' => 1,
//                'user_id' => $find['user_id'],
//                'type' => 0,
//                'tixian' => 0,
//                'order_id' => $find['orderid'],
//                'price' => $price
//            ]);
//            $addthree->save();

        }
    }
    /**
     * 安装与报装评价
     */
    public function mypl(){
        $data = $this->request->request('');
        if(empty($data['user_id']))$this->error('请登录');
        $user=\app\admin\model\BydUser::find($data['user_id']);
        if(empty($user))$this->error('用户信息不正确');
        $pl=BydShopPl::where('user_id',$data['user_id'])->where('state',$data['type'])->paginate(10);
        if(empty($pl))$this->error('暂无数据');
        $this->success('请求成功',['status'=>$pl]);
    }

    /**
  **积分商品购买
     */
    public function shoppay(){

        $data = $this->request->request('');

        $osn = $this->getOrderNumber();

        $user=\app\admin\model\BydUser::where( 'id',$data['user_id'])->find();
      if($user['score']<$data['price']){
          $this->error('积分不足,无法兑换');
      }
        $address=BydAddress::where('id',$data['addressid'])->find();//查询出地址
        //临时关系
        $tem=Temrela::where('user_id',$data['user_id'])->where('close',0)->find();
        if(empty($tem)){
            $tem['one']=0;
            $tem['two']=0;
            $tem['three']=0;
        }else{
            $tem['one']=$tem['pid'];
            $tem['two']=$tem['two'];
            $tem['three']=$tem['three'];
        }

        $uu=new BydUser();

        if($data['type']==0){
            $data['state']=1;//立即支付
        }else{
            $data['state']=0;//放弃支付
        }
        if($data['cuponsid']>0){
            $cup=BydCupon::where('id',$data['cuponsid'])->find();
            //$find=BydUsercupons::where('user_id',$data['user_id'])->where('coupons_id',$data['cuponsid'])->update(['state'=>1]);
            //if($cup['yh_price']>$data['price'])$this->error(__('优惠劵不可用'));
            $price=$data['price']+$data['dj'];
            $yh=$cup['yh_price'];
        }else{
            $price=$data['price']+$data['dj'];
            $yh=0;
        }
        $price=floor($price*100)/100;

        //$bl=\app\admin\model\BydShopOrder::find();

        if($data['cartid']==0){
            $productLists=db('byd_shop')->where('id',$data['shopid'])->find();

//            $first=$data['price']*$bl['first']/100;

            $adds = new BydShopOrder();

            $adds->data([
                'dzg'=>$data['dzg'],
                'score'=>1,
                'orderid'  => $osn,
                'one'  =>  $tem['one'],
                'two'  =>  $tem['two'],
                'three'  =>  $tem['three'],
                'deposit'  =>  $data['dj'],
                'user_id'  => $data['user_id'],
                'state' =>  1,
                'productid' =>  $data['shopid'],
                'num' =>   $data['num'],
                'cuponsid'=>$data['cuponsid'],
                'price' => $price,// $data['price']
                'yh_price' => $yh,// $data['price']
                'addressid' =>   $data['addressid'],
                'address' =>   $address['title'],
                'addressxq' =>   $address['address'],
                'phone' =>   $address['phone'],
                'special' =>   $data['specid'],
                'specidsize' => $data['specidsize'],
                'username'=>$address['username'],
                'content'=>$data['content']
            ]);

            $adds->save();

            $add = new BydOrderSon();

            $add->data([
                'productname'=>$productLists['name'],
                'good_code'=>$productLists['good_code'],
                'porderid'  => $osn,
                'fwbl'  => $productLists['fwbl'],
                'tcbl'  => $productLists['tcbl'],
                'user_id'  => $data['user_id'],
                'state' =>  0,
                'productid' =>  $data['shopid'],
                'num' =>   $data['num'],
                'price' =>  $data['price'],
                // 'addressid' =>   $data['addressid'],
                'address' =>   $address['title'],
                //'addressxq' =>   $address['address'],
                //'phone' =>   $address['phone'],
                'special' =>   $data['specid'],
                'specidsize' => $data['specidsize'],
                'username'=>$address['username']
            ]);
            $add->save();
            if($add){
                $name=$data['specidsize'];
                \think\Cache::set('xd',1,3600);
                //微信支付
                $addscore=new Sorce();
                $addscore->data([
                    'name'=>"兑换$name",
                    'state'=>1,
                    'price'=>$data['price'],
                    'user_id'=>$data['user_id'],
                ]);
                $addscore->save();
                $screde=\app\admin\model\BydUser::where('id',$data['user_id'])->setDec('score',$data['price']);
                $this->success('兑换成功');
//                $config = [
//
//                    'app_id'    => 'wx00e9e5b843259a9d',
//
//                    'mch_id'    => '1584376091',
//
//                    'key'       => 'TjRUCktaUcR6RQqCksBtwKRY8KwSTC4M',
//
//                    'secret'    => 'cce6015196dbba888133f9a3613b18b7',
//
//                    'notify'    => 'http://bao.scwushen.com/index.php/api/notify/cg',
//
//                ];
//
//                $obj = new Wx( $config );
//
//                $money = $data['price'];//$data['price']
//
//                $data = [
//                    'body' => '宝云邸',
//                    'out_trade_no' => $osn, //客户订单号,
//                    'total_fee'=> $money * 100,
//                    'trade_type'    => 'JSAPI',
//                    'openid'    => $user['openid'],
//                ];
//                $ret = $obj->unifiedOrder( $data );
//                return json($ret);
//                $wxpay=new Wxpay();
//                $arr = [
//                    'user_id'=>$data['user_id'],
//                    'order_id'  => $osn,
//                    'openid' =>$user['openid'],
//                    'status'=>1
//                ];
//
//                $pay=$wxpay->pay($arr);
//               return json(['code'=>1,'msg'=>'请求成功','data'=>$pay]);

            }

        }else{
//查看是否为预约订单商品

            $cart=BydShopCart::where('id','in',$data['cartid'])->select();
            $prices=BydShopCart::where('id','in',$data['cartid'])->sum('price');
            if(empty($cart)){
                return json(['code'=>0,'msg'=>'数据错误']);
            }

            if(empty($data['orderid'])){

                $data['yyid']=0;
//                $yyorder=\app\admin\model\BydDesignerMake::where('user_id',$data['user_id'])->where('state',1)->find();
//                if(empty($yyorder))   $this->error(__('预约订单有误'));
//                //预约订单里面的商品
//            $data['yyid']=$yyorder['orderid'];//预约单号
            }else{
                $yyorder=\app\admin\model\BydDesignerMake::where('user_id',$data['user_id'])->where('state',1)->find();
                if(empty($yyorder))   $this->error(__('预约订单有误'));
                //预约订单里面的商品
                $data['yyid']=$yyorder['orderid'];//预约单号

                $data['price']=$data['price']+$yyorder['price'];
//                $data['yyid']=0;
            }
            $add = new BydShopOrder();

//            foreach ($cart as $v){

            $add->data([
                'dzg'=>$data['dzg'],
                'orderid'  => $osn,
                'yyid'  => $data['yyid'],
                'user_id'  => $data['user_id'],
                'state' =>  0,
                'deposit'  =>  $data['dj'],
                'one'  =>  $tem['one'],
                'two'  =>  $tem['two'],
                'three'  =>  $tem['three'],
                //'productid' =>  $str,
                'num' =>   $data['num'],
                'swj'=>$data['swj'],
//                'jfprice' =>  $cart['jfprice']*$cart['num'],

                'cuponsid'=>$data['cuponsid'],
                'price' => $price,// $data['price']
                'yh_price' => $yh,// $data['price']

                'phone' =>   $address['phone'],

                'addressid' =>   $data['addressid'],

                'address' =>   $address['title'],

                'addressxq' =>   $address['address'],

                'username'=>$address['username'],

                'content'=>$data['content']


//                'state' =>   $data['state'],

//                'special' =>   $cart['specid'],

//                'specidsize' => $cart['specidsize'],

            ]);

            $add->save();

            if($add){
                \think\Cache::set('xd',1,3600);
//                foreach ($cart as $v){

////                    $id[]=$v['id'];

////                    $shopid[]=$v['shopid'];

//                }

            };

            foreach ($cart as $v){
                $productLists=db('byd_shop')->where('id',$v['shopid'])->find();

                $adds=new BydOrderSon();

//                $id[]=$v['id'];

//                $shopid[]=$v['shopid'];

                $adds->data([
                    'productname'=>$productLists['name'],
                    'good_code'=>$productLists['good_code'],
                    'porderid'  => $osn,
                    'fwbl'  => $productLists['fwbl'],
                    'tcbl'  => $productLists['tcbl'],
                    'user_id'  => $data['user_id'],

                    'state' =>  0,

                    'productid' =>  $v['shopid'],

                    'num' =>   $v['num'],

//                'jfprice' =>  $cart['jfprice']*$cart['num'],

                    'price' =>   $v['price'],

                    'addressid' =>   $data['addressid'],

                    'address' =>   $address['title'],

                    'addressxq' =>   $address['address'],

//                    'username'=>$address['username']

//                'state' =>   $data['state'],

                    'specid' =>   $v['specid'],
                    'special' =>   $v['specid'],

                    'specidsize' => $v['specidsize'],

                ]);

                $adds->save();

            }

            // $str = implode(",", $shopid);

//            print_r($cart);die;



//            foreach ($cart as $v){



            if($add){

                $deal=BydShopCart::where('id','in',$data['cartid'])->delete();

                //微信支付
                $config = [

                    'app_id'    => 'wx00e9e5b843259a9d',

                    'mch_id'    => '1584376091',

                    'key'       => 'TjRUCktaUcR6RQqCksBtwKRY8KwSTC4M',

                    'secret'    => 'cce6015196dbba888133f9a3613b18b7',

                    'notify'    => 'http://bao.scwushen.com/index.php/api/notify/cg',

                ];

                $obj = new Wx( $config );

                $money = $price;

                $data = [

                    'body' => '宝云邸',

                    'out_trade_no' => $osn, //客户订单号,

                    'total_fee'=> $money * 100,

                    'trade_type'    => 'JSAPI',

                    'openid'    => $user['openid'],

                ];

                $ret = $obj->unifiedOrder( $data );



                //$deal=BydShopCart::destroy($data['cartid']);//删除购物车里面的数据

                return json($ret);

            }

//            $save['xfscore']=$user['xfscore']-$cart['jfprice'];

//            $wheree['id']=$data['user_id'];

//            $xfscore=$uu->isUpdate(true,($wheree))->save($save);



//            }

        }



    }
 /**
  * 7天后加积分
  */
  public function addscore(){
      $arr=BydShopOrder::where('okscore',0)->select();
      if(!empty($arr)){

          foreach ($arr as $v){
              if(!empty($v['oktime']) && $v['oktime']<time()){
                  $update=BydShopOrder::where('id',$v['id'])->update(['okscore'=>1]);
                  $score =\app\admin\model\BydUser::where('id',$v['user_id'])->setInc('score', $v['price']);
                  $allscore =\app\admin\model\BydUser::where('id',$v['user_id'])->setInc('allscore', $v['price']);
                  $addsorce=new Sorce();
            $addsorce->data([
                'name'=>'购买商品',
                'user_id'=>$v['user_id'],
                'state'=>0,
                'price'=>$v['price'],
            ]);
            $addsorce->save();
              }
          }
      }
  }
}